如何在屬性值更改時引發事件
您想要一個名為ImageFullPath1 的屬性每當其值發生變化時引發一個事件。雖然您知道使用 INotifyPropertyChanged 接口,但您更喜歡利用事件來實現此目的。
INotifyPropertyChanged 介面其實是透過事件實現的。它有一個成員,PropertyChanged,這是一個可以由消費者訂閱的事件。
安全實作:
以下程式碼片段示範了 INotifyPropertyChanged介面的安全實現,以及特定屬性的附加事件(ImageFullPath):
public class MyClass : INotifyPropertyChanged { private string imageFullPath; protected void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, e); } protected void OnPropertyChanged(string propertyName) { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } public string ImageFullPath { get { return imageFullPath; } set { if (value != imageFullPath) { imageFullPath = value; OnPropertyChanged("ImageFullPath"); } } } protected void OnImageFullPathChanged(EventArgs e) { EventHandler handler = ImageFullPathChanged; if (handler != null) handler(this, e); } public event PropertyChangedEventHandler PropertyChanged; public event EventHandler ImageFullPathChanged; }
此實現確保以下內容:
.NET 4.5 中的CallerMM完成>
。 🎜>對於.NET 4.5及更高版本,CallerMemberAttribute可用於消除硬編碼字串原始碼中的屬性名稱:
以上是如何在 C# 中屬性值變更時引發自訂事件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!