【问题标题】:WPF Binding INotifyPropertyChangedWPF 绑定 INotifyPropertyChanged
【发布时间】:2014-04-10 07:35:37
【问题描述】:

我有一个理论问题。

<ListBox ItemSource= "{Binding Fruits}" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Color}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox

假设我的 ViewModel 中有 ObservableCollection&lt;Fruit&gt; Fruits。 水果不是我的课,所以当水果颜色发生变化时我无法实现INotifyPropertyChanged。 当这些属性发生更改时,我在我的 ViewModel 中知道:

public ChangeColor()
{
Fruits[1].Color = "Blue";
//Notify Fruits Here, How?
}
  1. 怎么做?
  2. 在后台实现INotifyPropertyChanged 时它是如何工作的?如果我有 ObservableCollection&lt;Fruit&gt; Fruits 并且 Fruit Color 属性发生更改,则会发送类似 NotifyPropertyChanged("Fruits.Name") 的内容?

【问题讨论】:

  • 将您的 Fruit 包装在封装 Fruit 并添加 INotifyPropertyChanged-Functionality 的 Fruit 中,以便在颜色更改时引发 PropertyChangedEvent
  • 另外,您可以查看面向方面的编程 (AOP),只需 google POSTSHARP。根据上面的建议,将你的 M 包装在 VM 中的方法要长得多。
  • 好的,没错。但是第二个问题呢?如何通过在 ViewModel 中调用事件来更新 ItemsSource 中的每种颜色?

标签: wpf binding inotifypropertychanged


【解决方案1】:
  1. “Fruit 不是我的类”,你的意思是 Fruit 类是别人写的还是封装在某个 dll 中?如果是这样,您仍然可以继承 Fruit 并实现 INotifyPropertyChanged 接口,例如: 公共类 FruitsEx : Fruits, INotifyPropertyChanged { 公共颜色 ColorEx { 得到{返回这个。颜色; } 放 { this.Color = 值;
    if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("ColorEx")); } } } // INotifyPropertyChanged 事件 公共事件 PropertyChangedEventHandler PropertyChanged; 公共无效NotifyPropertyChanged(字符串属性名称) { if (PropertyChanged != null) {
    PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }

这样,您可以使用 ColorEx 属性来通知更改。

  1. INotifyPropertyChanged 和 ObservableCollection 有不同的用途。 ObservableCollection 将在集合中的项目更改(例如,添加或删除)时更新目标列表。但是,如果您想更改集合中某个项目的颜色,则需要为该项目实现 INotifyPropertyChanged。

要记住的一点是,如果你这样做了

new ObservableCollection<T>()

目标不会更新。因为 ObservableCollection 本身并没有实现通知机制。

【讨论】:

  • 您可以在代码的缩进上多加四个空格,以使其与有序列表一起使用。事实上,它很难阅读。
  • @EdPlunkett 是的,谢谢,我注意到了。但是不知道我的chrome浏览器有没有问题。额外的四个空格拒绝工作。我放了一个额外的
     标签让它看起来更好。
【解决方案2】:

正如 Jehof 在 cmets 中提到的,这里的关键是创建一个 FruitViewModel 来包装您的水果模型。 在这种情况下,您需要告诉特定的 FruitviewModel 在其属性之一上调用 OnPropertyChanged 才能工作。 ("Fruits.Name") 将不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    • 2013-07-31
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多