您好,我正在尝试使用 NotifyPropertyChanged 来更新我绑定(bind)属性的所有位置。对于我搜索过的内容,INotifyPropertyChanged 是针对这种情况指示的。
所以我需要帮助,因为我不明白我在这里有什么问题。我真的不知道如何处理 PropertyChange 事件。我的问题是,他什么时候改变?我还需要他做什么?
数据网格:
<ListView Name="listView" ItemsSource="{Binding Categories}"/>
我更改类别属性时的示例:
DataTest dtTest = new DataTest();
public MainWindow()
{
InitializeComponent();
this.DataContext = dtTest;
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
//Here i pick up a string from a textBox, where i will insert in a Table of my DB,
//Then i will do a query to my Table, and i will get a DataTable for example
//Then i just put the contents into the DataView, so the value have changed.
dtTest.Categories = dtTable.DefaultView;
dtTest = dtTable.defaultView; (this only an example, i don't this for real.)
//What i have to do now, to wherever i am binding (DataGrid, ListView, ComboBox)
//the property to the new values automatically being showed in all places?
}
我的类(class):
public class DataTest : INotifyPropertyChanged
{
private DataView categories;
public event PropertyChangedEventHandler PropertyChanged; //What i have to do with this?
private void NotifyPropertyChanged(string str)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(str));
}
}
public DataView Categories
{
get { return categories; }
set
{
if (value != categories)
{
categorias = value;
NotifyPropertyChanged("Categories");
}
}
}
}
我的类(class)有 INotifyCollectionChanged:
public class DataTest : INotifyCollectionChanged
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
private void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
{
CollectionChanged(this, e);
}
}
public DataView Categories
{
get { return categories; }
set
{
if (value != categories)
{
categories = value;
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, Categories));
}
}
}
}
但为什么 PropertyChanged 总是 NULL???我必须做更多的事情,但我不知道该做什么。
提前致谢!
最佳答案
DataTest
类需要是绑定(bind)的 DataContext
。您可以在代码隐藏中设置它(或无数其他方式,但为简单起见 - 只需在代码隐藏中进行)
public MainWindow() // constructor
{
this.DataContext = new DataTest();
}
然后,使用绑定(bind)集的“源”,您可以指定“路径”,因此您的 xaml 如下所示:
<ListBox ItemsSource="{Binding Categories}" />
现在,如果属性“Categories”在代码中发生更改,您编写的 NotifyPropertyChanged
代码将提醒 Binding,Binding 反过来将访问该属性的公共(public) getter 并刷新 View 。
关于c# - 在 WPF 中使用 INotifyPropertyChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5785265/