如何在更改项属性时更新ObservableCollection

时间:2017-06-16 23:02:06

标签: c# xaml binding observablecollection

我已经多次发布(并回答)这个问题了,我似乎还无法弄清楚我错过了什么......

我有一个带有复选框列表的窗口,我希望能够从代码隐藏中动态启用/禁用列表中的复选框。为此,我有几个单选按钮调用代码隐藏功能来切换VisibleFeatures集合中第一个条目的“Enabled”属性。理想情况下,这会导致第一个复选框+文本启用/禁用,但不会发生UI更改。

我做错了什么?

视图模型:

public class MyFeature
{
   private bool _supported;
   private bool _enabled;
   private bool _selected;
   public string Name { get; set; }

   public bool Supported
   {
      get { return _supported; }
      set { _supported = value; NotifyPropertyChanged("Supported"); }
   }
   public bool Enabled
   {
      get { return _enabled; }
      set { _visible = value; NotifyPropertyChanged("Enabled"); }
   }
   public bool Selected
   {
      get { return _selected; }
      set { _selected = value; NotifyPropertyChanged("Selected"); }
   }

   public MyFeature(string name)
   {
      Name = name;
      _supported = false;
      _enabled = false;
      _selected = false;
   }

   public event PropertyChangedEventHandler PropertyChanged;
   private void NotifyPropertyChanged(string propertyName)
   {
      if (PropertyChanged != null)
      {
         PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
   }
}

public ObservableCollection<MyFeature> VisibleFeatures { get; set; }

void VisibleFeatures_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
   if (e.NewItems != null)
      foreach (MyFeature item in e.NewItems)
         item.PropertyChanged += MyFeature_PropertyChanged;

   if (e.OldItems != null)
      foreach (MyFeature item in e.OldItems)
         item.PropertyChanged -= MyFeature_PropertyChanged;
}

void MyFeature_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
   // NotifyPropertyChanged() defined again elsewhere in the class
   NotifyPropertyChanged("VisibleFeatures");
}

public Init()
{
   VisibleFeatures = new ObservableCollection<MyFeature>();
   VisibleFeatures.CollectionChanged += VisibleFeatures_CollectionChanged;
   VisibleFeatures.Add(new MyFeature("Feature1"));
   VisibleFeatures.Add(new MyFeature("Feature2"));
   ...
}

XAML:

<StackPanel>
   <ListView ItemsSource="{Binding VisibleFeatures}">
      <ListBox.ItemTemplate>
         <DataTemplate>
            <StackPanel IsEnabled="{Binding Enabled, Mode=TwoWay}">
               <CheckBox IsChecked="{Binding Selected, Mode=TwoWay}">
                  <TextBlock Text="{Binding Name}" />
               </CheckBox>
            </StackPanel>
         </DataTemplate>
      </ListBox.ItemTemplate>
   </ListView>
</StackPanel>

2 个答案:

答案 0 :(得分:2)

您的类MyFeature需要声明它实现了接口INotifyPropertyChanged。否则,XAML将不会生成监听器来收听您的属性更改通知。

此外,从您的示例中,我看到没有使用通知VisibleFeatures更改。

答案 1 :(得分:1)

推导你的课程&#34; MyFeature&#34;来自INotifyPropertyChanged界面。

为了反映您在视图中的可观察集合中所做的运行时更改,必须从INotifyPropertyChanged接口派生您的viewmodel类(此处为MyFeature类)。

此外,建议在任何地方使用绑定属性的相同实例,而不是创建新实例。