반응형
위 블로그를 참고했다.
MVVM을 이용하여 버튼을 누르면 아래 텍스트 박스에 (위 텍스트 박스에 적힌 수+1)이 나타나는 프로그램을 작성했다.
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>
</StackPanel>
</Grid>
</Window>
Command.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace TmpWpfApp1
{
internal class Command : ICommand
{
private Action<object> __executeAction;
public event EventHandler CanExecuteChanged;
public Command(Action<object> executeAction)
{
__executeAction = executeAction;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
__executeAction?.Invoke(parameter);
}
}
}
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();
}
}
}
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 Model1 { get; set; } = new MainModel();
public Command ButtonCmd { get; set; }
public MainViewModel()
{
ButtonCmd = new Command(x => Model1.Y = (byte)(Model1.X + 1));
}
}
}
반응형
'MVVM' 카테고리의 다른 글
MVVM(3) Button 하나, TextBox 둘, DataGrid 하나 (0) | 2024.12.20 |
---|---|
MVVM(1) 두 개의 TextBox (0) | 2024.12.20 |