반응형
아래 블로그를 참고해서 만들었다.
[WPF][MVVM][Study] MVVM 실습 1 - 단위 변환기
두 개의 텍스트 박스가 있는데, 위 텍스트 박스에 X=0~255를 입력하면 아래 텍스트 박스에 X+1이 출력되는 매우 단순한 GUI 프로그램을 MVVM으로 만들었다.
MainWindow.xaml
<Window x:Class="TmpWpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TmpWpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800"
Background="Black"
xmlns:vm="clr-namespace:TmpWpfApp1.ViewModel">
<Window.DataContext>
<vm:MainViewModel/>
</Window.DataContext>
<Grid>
<StackPanel>
<TextBox Text="{Binding Model.X, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Text="{Binding Model.Y, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
</Grid>
</Window>
Model/MainModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace TmpWpfApp1.Model
{
internal class MainModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName]string name=null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private byte x;
public byte X
{
get => x;
set
{
if(x != value)
{
x = value;
OnPropertyChanged();
Y = (byte)(x + 1);
}
}
}
private byte y;
public byte Y
{
get => y;
set
{
if(y != value)
{
y = value;
OnPropertyChanged();
}
}
}
}
}
ViewModel/MainViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TmpWpfApp1.Model;
namespace TmpWpfApp1.ViewModel
{
internal class MainViewModel
{
public MainModel Model { get; set; } = new MainModel();
}
}
참고로, DataContext에 넣을 클래스(위에선 ViewModel)는 internal이어도 되지만, DataContext의 속성(위에선 Model)은 반드시 public이어야만 한다. public이 아니면 바인딩이 제대로 작동을 하지 않는다.
클래스의 생성자는 internal이어도 된다. 근데 internal로 생성자를 선언하면 xaml 편집할 때
Error XDG0003 이 개체에 대해 매개 변수가 없는 생성자가 정의되지 않았습니다.
이런 오류가 뜰 수 있다. 그러나 제대로 컴파일은 된다. 바인딩도 잘 된다.
반응형
'MVVM' 카테고리의 다른 글
MVVM(3) Button 하나, TextBox 둘, DataGrid 하나 (0) | 2024.12.20 |
---|---|
MVVM(2) TextBox 둘, Button 하나 (0) | 2024.12.20 |