我试图将ObservableCollection<FilterControlViewmodel>
中的每个视图模型作为DataContext
绑定到FilterControl
中的用户控件ItemsControl
。
绑定本身可以正常工作。 "InitialFilterName"
已从FilterControlViewmodel.FilterName
正确显示,但是该属性的任何更新都不会通知UI。
还在ObservableCollection<FilterControlViewmodel>
中添加元素也可以查找并添加其他用户控件。但是,FilterControlViewmodel
内的值仍然不会更新到UI。
任何有关缺少通知的提示都将受到赞赏。谢谢。
MainWindow.xaml
<Window.DataContext>
<local:MainWindowViewmodel/>
</Window.DataContext>
<Grid>
<ItemsControl ItemsSource="{Binding FilterViewmodel.FilterControls}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<filter:FilterControl DataContext="{Binding}"></filter:FilterControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
FilterControl.xaml
<UserControl.DataContext>
<local:FilterControlViewmodel/>
</UserControl.DataContext>
<Grid>
<Label Grid.Column="0" Grid.Row="0" Content="{Binding FilterName}"></Label>
<ComboBox Grid.Column="0" Grid.Row="1" ItemsSource="{Binding FilterValues}" SelectedItem="{Binding FilterValueSelected}"></ComboBox>
<Button Grid.Column="1" Grid.Row="1" Content="X" Command="{Binding ResetFilterCommand}"></Button>
</Grid>
MainWindowViewmodel.cs
public class MainWindowViewmodel : INotifyPropertyChanged
{
public FilterViewmodel FilterViewmodel
{
get => _filterViewmodel;
set
{
if (Equals(value, _filterViewmodel)) return;
_filterViewmodel = value;
OnPropertyChanged();
}
}
FilterViewmodel.cs
public class FilterViewmodel : INotifyPropertyChanged
{
public ObservableCollection<FilterControlViewmodel> FilterControls
{
get => return _filterControls;
set
{
if (Equals(value, _filterControls)) return;
_filterControls = value;
OnPropertyChanged();
}
}
FilterControlViewmodel.cs
public class FilterControlViewmodel : INotifyPropertyChanged
{
private string _filterName = "InitialFilterName";
public string FilterName
{
get => _filterName;
set
{
if (value == _filterName) return;
_filterName = value;
OnPropertyChanged();
}
}
答案 0 :(得分:1)
您应删除以下标记,因为它会创建FilterControlViewmodel
的另一个实例:
<UserControl.DataContext>
<local:FilterControlViewmodel/>
</UserControl.DataContext>
然后,FilterControl
将从DataContext
中当前项(FilterControlViewmodel
)继承其ItemsControl
,而不必显式设置DataContext
属性:
<ItemsControl ItemsSource="{Binding FilterViewmodel.FilterControls}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<filter:FilterControl/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>