Etc/Test

WPF INotifyPropertyChanged

김컴맹 2023. 4. 6. 14:24
반응형

WPF (Windows Presentation Foundation)에서 데이터 바인딩을 사용할 때, 데이터 모델의 속성 값이 변경될 때마다 UI 요소를 자동으로 업데이트하려면 INotifyPropertyChanged 인터페이스를 구현해야 합니다.

INotifyPropertyChanged 인터페이스는, 데이터 모델의 속성 값이 변경될 때 이를 알리기 위한 이벤트를 정의하는 인터페이스입니다. 이 인터페이스를 구현하면, UI 요소가 데이터 모델의 속성 값에 바인딩될 때, 데이터 모델의 속성 값이 변경될 때마다 이벤트를 발생시켜 UI 요소를 자동으로 업데이트할 수 있습니다.

INotifyPropertyChanged 인터페이스를 구현하려면, 다음과 같은 코드를 작성해야 합니다.

public class MyViewModel : INotifyPropertyChanged
{
    private string myProperty;

    public string MyProperty
    {
        get { return myProperty; }
        set
        {
            if (myProperty != value)
            {
                myProperty = value;
                OnPropertyChanged("MyProperty");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}


위 코드에서, MyViewModel 클래스는 INotifyPropertyChanged 인터페이스를 구현합니다. MyProperty 속성은 INotifyPropertyChanged 인터페이스를 사용하여 구현되며, 속성 값이 변경될 때마다 OnPropertyChanged 메서드를 호출하여 PropertyChanged 이벤트를 발생시킵니다.

이렇게 구현된 데이터 모델을 사용하여 UI 요소에 데이터 바인딩을 설정하면, UI 요소는 데이터 모델의 속성 값이 변경될 때마다 자동으로 업데이트됩니다. INotifyPropertyChanged 인터페이스를 구현함으로써, 데이터 모델과 UI 요소 간의 결합도를 낮추고 코드를 더욱 유연하게 작성할 수 있습니다.

반응형

'Etc > Test' 카테고리의 다른 글

레이트레이싱(Ray Tracing)  (0) 2023.04.07
OCI Instance Run command의 Delivery State  (0) 2023.04.06
WPF DataBinding  (0) 2023.04.06
Array, ArrayList, List의 차이점  (0) 2023.04.06
convert mysql to sql server  (0) 2023.04.04