为什么在WPF中使用带有绑定的INotifyPropertyChanged?

我已经注意到,几乎我在互联网上找到的关于绑定的每个例子都有一个类(绑定到另一个属性),它inheritance了INotifyPropertyChanged接口,并在类’属性的set部分中使用了一个方法。

我已经尝试从绑定示例中删除该部分,并且它与该方法的工作方式相同。

这是一个例子。 我已经对它进行了修改,因此它将是一个TwoWay绑定模式,并在消息框中显示已更改的属性。

我这样做只是为了玩一点点绑定,但现在我真的不知道为什么使用该接口

编辑

XAML:

                                 

Main.cs:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication1 { ///  /// Interaction logic for MainWindow.xaml ///  public partial class MainWindow : Window { Binding bind; MyData mydata; public MainWindow() { InitializeComponent(); } private void btnBinding_Click(object sender, RoutedEventArgs e) { mydata = new MyData("T"); bind = new Binding("MyDataProperty") { Source = mydata, Mode = BindingMode.TwoWay }; txtBinding.SetBinding(TextBox.TextProperty, bind); } private void btnMessage_Click(object sender, RoutedEventArgs e) { MessageBox.Show(mydata.MyDataProperty); } private void btnChangeproperty_Click(object sender, RoutedEventArgs e) { mydata.MyDataProperty = "New Binding"; } } } 

MyData类:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace WpfApplication1 { public class MyData { private string myDataProperty; public MyData() { } public MyData(DateTime dateTime) { myDataProperty = "Last bound time was " + dateTime.ToLongTimeString(); } public MyData(string teste) { myDataProperty = teste; } public String MyDataProperty { get { return myDataProperty; } set { myDataProperty = value; OnPropertyChanged("MyDataProperty"); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string info) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(info)); } } } } 

如果您只打算使用绑定来写入属性(如您所知),则不需要INotifyPropertyChanged ,但您确实需要它以便您可以告诉其他人写入属性并相应地更新显示的值。

要查看我正在谈论的内容,请在窗口中添加一个按钮,单击此按钮可直接更改绑定属性的值( 而不是绑定到该属性的UI元素的相应属性)。 使用INotifyPropertyChanged ,当您单击按钮时,您将看到UI将自身更新为新值; 没有它,UI仍将显示“旧”值。

从这里的讨论来看,我认为你错过了实施

 RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(“Propety Name”)) 

实现后,您可以看到UI正在自动更新。 您可以在我的博客上查看MSDN或简短版本的详细信息。