首页 文章

将DataContext设置为XAML中的当前代码隐藏对象

提问于
浏览
4

我正在尝试将UserControl的DataContext设置为UserControl的代码隐藏类 . 从代码隐藏方面来看,这很容易做到:

public partial class OHMDataPage : UserControl
{
    public StringList Stuff { get; set; }

    public OHMDataPage ()
    {
        InitializeComponent();

        DataContext = this;
    }
}
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Class="LCDHardwareMonitor.Pages.OHMDataPage">

    <ScrollViewer>
        <ListBox ItemsSource="{Binding Stuff}" />
    </ScrollViewer>

</UserControl>

但是,我怎样才能完全从XAML端和UserControl级别执行此操作?如果我这样做,它适用于子节点(并从代码隐藏中删除 DataContext = this; ):

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Class="LCDHardwareMonitor.Pages.OHMDataPage">

    <ScrollViewer
        DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}">
        <ListBox ItemsSource="{Binding Stuff}" />
    </ScrollViewer>

</UserControl>

我真的很想了解如何在UserControl本身上执行此操作 . 我希望这可行:

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Class="LCDHardwareMonitor.Pages.OHMDataPage"
    DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">

    <ScrollViewer>
        <ListBox ItemsSource="{Binding Stuff}" />
    </ScrollViewer>

</UserControl>

但事实并非如此 .

1 回答

  • 6
    DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}}"
    

    应该管用 .

    但是如果在调用 InitializeComponent() 之前未设置属性,则WPF绑定机制不会更改't know that your property'的值 .

    为了给你一个快速的想法:

    // the binding should work
    public StringList Stuff { get; set; }
    public Constructor()
    {
        Stuff = new StringList { "blah", "blah", "foo", "bar" };
        InitializeComponent();
    }
    
    // the binding won't work
    public StringList Stuff { get; set; }
    public Constructor()
    {
        InitializeComponent();
        Stuff = new StringList { "blah", "blah", "foo", "bar" };
    }
    

    如果您使用的是字符串列表,请考虑使用 ObservableCollection . 这将在添加或删除项目时通知WPF绑定机制 .

相关问题