我实现了一个模型类,并希望在修改对象时为所有子属性引发PropertyChanged事件。但我发现它不起作用。当我按下按钮时,标签的文字没有改变。我错过了什么吗?我从MSDN得到了这个 - " PropertyChanged事件可以指示对象上的所有属性都已更改使用null或String.Empty作为PropertyChangedEventArgs中的属性名称。" 该平台是.net framework 4.0和VS2015
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Model = new Model()
{
data = new User()
{
Name = "test"
}
};
label1.DataBindings.Add("Text", Model.data, "Name", false, DataSourceUpdateMode.OnPropertyChanged);
}
private Model model;
public Model Model
{
get
{
return this.model;
}
set
{
model = value;
}
}
private void button1_Click(object sender, EventArgs e)
{
User temp = new User()
{
Name = "test1"
};
Model.data = temp;
}
}
public class NotifyPropertyChanged : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetField<T>(ref T field, T value, string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
OnPropertyChanged(null);
return true;
}
}
public class Model : NotifyPropertyChanged
{
private User m_data;
public User data
{
get { return m_data; }
set
{
SetField(ref m_data, value,"data");
}
}
}
public class User : NotifyPropertyChanged
{
private string name;
public string Name
{
get { return this.name; }
set
{
SetField(ref name, value, "Name");
}
}
private string tel;
public string Tel
{
get { return this.tel; }
set
{
SetField(ref tel, value, "Tel");
}
}
}
答案 0 :(得分:0)
您的问题是您对Model.data
的绑定,但稍后会为其指定一个新值
因此,不再使用由绑定监视的实例。
您有2个选项:
第一个:不要创建新的User
,只需更改Name
:
private void button1_Click(object sender, EventArgs e)
{
Model.data.Name = "test1";
}
或者,如果您确实需要支持两种情况(创建和分配),则必须将绑定更改为Model
并从data.Name
获取文本:
label1.DataBindings.Add("Text", Model, "data.Name", false,
DataSourceUpdateMode.OnPropertyChanged);
此set
中User
属性的Model
部分:
set
{
SetField(ref m_data, value, "data");
this.data.PropertyChanged += (sender, args) => this.OnPropertyChanged("data");
}
因此,如果PropertyChanged
已更改,则会在数据上创建data.Name
,如果data
属性本身已set