项目模板内的用户控件的WPF更改通知不起作用

时间:2019-05-13 11:29:24

标签: c# wpf data-binding

我试图将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();
      }
   }

1 个答案:

答案 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>