ftl*_*l25 2 c# events delegates subscription inotifypropertychanged
新手问题.
我有两个c#类 - 一个代码类(比如CodeClass)和一个表单类(比如FormClass).在CodeClass中,我有许多函数可以用来定期更新类中的字符串(我可以使用属性或任何合适的属性).当这个字符串值改变时,我想要一些通知其他类的方法.即,我将尝试让FormClass订阅更改字符串消息上的事件,然后将值打印到文本框或类似.然而,在未来的某个时刻,我需要提供从CodeClass API函数-所以基本上我需要一种方法来通知所有订阅类的字符串消息(修改字符串信息不会的不会得到CodeClass以外的任何地方进行修改-它发生函数中在CodeClass中).我已尝试过事件和委托等,但这些似乎都是由修改字符串消息(属性)的外部类实现的.
问候等
您需要实现该INotifyPropertyChanged接口:
class CodeClass : INotifyPropertyChanged
{
private string _myProperty;
public string MyProperty
{
get { return _myProperty; }
set
{
_myProperty = value;
OnPropertyChanged("MyProperty");
}
}
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
在FormClass,你可以订阅这样的PropertyChanged事件:
codeClass.PropertyChanged += codeClass_PropertyChanged;
...
void codeClass_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName = "MyProperty")
{
...
}
}
Run Code Online (Sandbox Code Playgroud)