PropertyChanged方法赋值



我已经为一个简单的WPF视图-视图模型实现了INotifyPropertyChanged接口,当我调用我的

protected void RaisePropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

设置为

this.RaisePropertyChanged("GoodText");

PropertyChanged事件有一个我从未分配给它的方法。

何时被分配?谁干的?

编辑:

谢谢你,很棒的建议,但我想威廉的回答正是我想要的,我的意思是:当我说

<Button Content="Button" Command="{Binding CheckButtonCommand}" />

类似于(丑陋的伪代码)

PropertyChanged += Button.GiveMeThePropertyValue;

?那么绑定将处理程序添加到PropertyChanged事件?

最有可能的是,属性(以及类)是在XAML中(或通过代码)绑定的数据。

如果绑定到一个实现INotifyPropertyChanged的类,那么绑定到源类的UIElement将会连接一个事件处理程序,以便能够监视属性的更改。

这就是"类字段事件"的魔力和委托的魔力。

首先是类字段事件:对于外部调用者,它们看起来像event -具有add/remove访问器;它们只能与+=/-=一起使用。然而,对于声明类型来说,它们看起来更像是字段—因此您可以直接访问委托。包括读取和赋值。

至于方法的来源。这就是(某种程度上)委托是什么。这实际上是委托实例上的.Invoke(...);但.Invoke是隐含的。这发生在任何委托,例如:

Action<string> action = s => Console.WriteLine(s);
// following are identical (but with different values, obviously)
action("hello");
action.Invoke("world");

有几个建议:

1:目前有一个非常小的不太可能咬你的线程竞赛;我建议:

var handler = PropertyChanged;
if(handler != null) handler(this, ...);

2:在最近的编译器中,你可以避免使用文字:

protected void RaisePropertyChanged([CallerMemberName] string propertyName=null)
{
    var handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

允许您从GoodText属性简单地调用它,如:

this.RaisePropertyChanged();

更少的代码=更少的错误(复制/粘贴名称等)

最新更新