이벤트를 사용하여 속성 값 변경을 알리는 방법
속성 값 변경을 관찰하려면 PropertyChanged 이벤트가 포함된 INotifyPropertyChanged 인터페이스를 활용할 수 있습니다. . 소비자는 이 이벤트를 구독하여 특정 속성의 변경 사항을 감지할 수 있습니다.
public interface INotifyPropertyChanged { event PropertyChangedEventHandler PropertyChanged; }
이벤트를 사용한 INotifyPropertyChanged의 안전한 구현
Richard의 이전 응답에서는 안전하지 않은 구현이 도입되었습니다. , 스레드 안전성을 보장하는 개정 버전은 다음과 같습니다.
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"); } } } public event PropertyChangedEventHandler PropertyChanged; }
이것은 구현:
추가 특정 속성 변경 이벤트
추가 세부성을 위해 다음과 같이 특정 속성에 대해 별도의 이벤트를 정의할 수 있습니다.
protected void OnImageFullPathChanged(EventArgs e) { EventHandler handler = ImageFullPathChanged; if (handler != null) handler(this, e); } public event EventHandler ImageFullPathChanged;
속성 setter에서 일반 OnPropertyChanged 이벤트와 특정 OnImageFullPathChanged를 모두 호출합니다. event.
속성 이름 획득 단순화(C# 4.5 전용)
마지막으로 C# 4.5 이상의 경우 CallerMemberAttribute를 활용하여 자동으로 속성 이름을 추출하므로 필요가 없습니다. 수동 문자열 리터럴의 경우:
protected void OnPropertyChanged( [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "") { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); }
위 내용은 속성 값 변경 알림을 위해 INotifyPropertyChanged를 안전하게 구현하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!