我正在尝试将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级别上实现这一点呢?如果我这样做(并从code-behind中删除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>
但是它并没有。
DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}"
在我的 MainWindow 上可以工作,但在这个 UserControl 上却不行。这很奇怪... - Adam