我正在尝试将UserControl的DataContext设置为UserControl的代码隐藏类.从代码隐藏方面来看,这很容易做到:
public partial class OHMDataPage : UserControl
{
public StringList Stuff { get; set; }
public OHMDataPage ()
{
InitializeComponent();
DataContext = this;
}
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
但是,我怎样才能完全从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>
Run Code Online (Sandbox Code Playgroud)
我真的很想了解如何在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>
Run Code Online (Sandbox Code Playgroud)
但事实并非如此.
DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}}"
Run Code Online (Sandbox Code Playgroud)
应该管用.
但是如果在InitializeComponent()调用之前未设置属性,则WPF绑定机制不知道您的属性的值已更改.
为了给你一个快速的想法:
// 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" };
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是字符串列表,请考虑使用ObservableCollection.这将在添加或删除项目时通知WPF绑定机制.