WPF – MVVM
MVVM

WPF에서
WPF
에서는 View
는 xaml
로 ViewModel
은 cs
로 완전히 분리된다.

View
xaml
로 위젯들을 구성하며 위젯이 표시할 내용을 ViewModel
로부터 참조한다.
<UserControl.DataContext>
<local:MyClass/>
</UserControl.DataContext>
XML위와 같이 DataContext
로 MyClass
를 지정하였다.
DataContext
가 지정되면 위젯은 바인딩을 통해 클래스의 프로퍼티를 참조하여 내용을 표시할 수 있다.
<TextBlock Text="{Binding Text}"/>
XMLTextBlock
위젯을 추가하고 이 위젯이 MyClass
의 Text
프로퍼티 텍스트를 표시하도록 바인딩 하였다.
ViewModel
View
에서 위젯들이 바인딩하여 표시할 프로퍼티들이 있는 클래스이다.
기본적으로 값이 변경될 때 View
로 Notify
되어야 View
에서 변경된 값으로 새롭게 갱신해서 표시를 해줄 수 있다.
따라서 ViewModel
클래스는 INotifyPropertyChanged
를 상속 받아야 한다.
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged( string propertyName )
{
PropertyChanged?.Invoke( this, new PropertyChangedEventArgs( propertyName ) );
}
}
C#View
에 바인딩된 프로퍼티는 값이 설정될 때마다 PropertyChangedEventHandler
를 통해서 View
에게 변경된 프로퍼티의 값을 전달한다.
private string _text;
public string Text;
{
get => _text;
set
{
if ( _text != value )
{
_text = value;
OnPropertyChanged( nameof( Text ) );
}
}
}
C#바인딩된 프로퍼티의 값이 변경될 때 Notify
하는 코드이다.
이전글 : WPF – Editor_WPF 프로젝트 추가
댓글을 남겨주세요
Want to join the discussion?Feel free to contribute!