プロパティの値が変更されたときにイベントを発生させる方法
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 の CallerMemberAttribute:
.NET 4.5 以降の場合、CallerMemberAttributeを排除するために使用できますソース コード内のプロパティ名のハードコーディングされた文字列:
protected void OnPropertyChanged( [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "") { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } public string ImageFullPath { get { return imageFullPath; } set { if (value != imageFullPath) { imageFullPath = value; OnPropertyChanged(); } } }
以上がC# でプロパティ値が変更されたときにカスタム イベントを発生させる方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。