我想在WPF中创建一个包含内容集合的用户控件,并努力让绑定在子元素上正常工作。我已经看了这个例子,但我一个层面更深入地嵌套,这和因此该方案并没有帮助:Data Binding in WPF User Controls如何处理包含列表的WPF用户控件中的嵌套绑定?
这里是我的用户:
<UserControl x:Class="BindingTest.MyList"
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"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
x:Name="uc">
<Grid>
<ListView Grid.Row="1" ItemsSource="{Binding Items, ElementName=uc}">
<ListView.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Text}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</UserControl>
而隐藏代码:
[ContentProperty("Items")]
public partial class MyList : UserControl {
public MyList() {
InitializeComponent();
}
public ObservableCollection<MyItem> Items { get; set; } = new ObservableCollection<MyItem>();
}
public class MyItem : DependencyObject {
public string Text {
get {
return (string)this.GetValue(TextProperty);
}
set {
this.SetValue(TextProperty, value);
}
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(MyItem), new PropertyMetadata());
}
然后我如何在应用程序中使用它:
<Window x:Class="BindingTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BindingTest"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Text="{Binding Val1, Mode=TwoWay}" />
<local:MyList Grid.Row="1">
<local:MyItem Text="{Binding Val1}" />
<local:MyItem Text="Two" />
<local:MyItem Text="Three" />
</local:MyList>
<ListView Grid.Row="2">
<ListViewItem Content="{Binding Val1}" />
<ListViewItem Content="Bravo" />
<ListViewItem Content="Charlie" />
</ListView>
</Grid>
</Window>
和FI应受我的窗口:
public partial class MainWindow : Window, INotifyPropertyChanged {
public MainWindow() {
InitializeComponent();
}
string _val1 = "Foo";
public string Val1 {
get { return _val1; }
set {
_val1 = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Val1"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
我现在遇到的问题是,第一个“MyItem”在用户控制最终显示的是空白的文本,而在库存控制显示美孚第一个ListViewItem如你所愿。
我明白这是因为在MyList控件中,DataTemplate为集合中的每个项目切换DataContext,但无论我在绑定表达式中尝试什么,无论是在窗口还是用户控件中,我都无法获取它正确绑定到窗口上的Val1。
我在做什么错?