반응형
아래 블로그를 참고하였다.
[WPF][MVVM][Study] MVVM 실습 3 - 학생 리스트 만들기
버튼을 누르면 위 텍스트 박스에 입력한 수 X에 1을 더한 수 Y를 아래 텍스트 박스에 출력하고, DataGrid에 (X, Y)가 적혀있는 행을 추가하는 프로그램을 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 Model1.X, UpdateSourceTrigger=PropertyChanged}" Margin="9"/>
<TextBox Text="{Binding Model1.Y, UpdateSourceTrigger=PropertyChanged}"/>
<Button Command="{Binding ButtonCmd}">click me</Button>
<DataGrid ItemsSource="{Binding Bytes}"/>
</StackPanel>
</Grid>
</Window>
ViewModel/MainViewModel.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TmpWpfApp1.Model;
namespace TmpWpfApp1.ViewModel
{
internal class MainViewModel
{
public MainModel Model1 { get; } = new MainModel();
public Command ButtonCmd { get; }
public ObservableCollection<KeyValuePair<byte,byte>> Bytes { get; } = new ObservableCollection<KeyValuePair<byte, byte>>();
public MainViewModel()
{
ButtonCmd = new Command(x =>
{
Model1.Y = (byte)(Model1.X + 1);
Bytes.Add(new KeyValuePair<byte, byte>(Model1.X, Model1.Y));
});
}
}
}
MainModel.cs와 Command.cs는 MVVM(2) 와 같다.
반응형
'MVVM' 카테고리의 다른 글
MVVM(2) TextBox 둘, Button 하나 (0) | 2024.12.20 |
---|---|
MVVM(1) 두 개의 TextBox (0) | 2024.12.20 |