MVVM 패턴은 처음 개발자로 입사하여 접했던 패턴이다.
개발을 처음 접했을 때는 전혀 이해가 안 되었지만 5년이 지난 지금은 가장 자신 있게 사용할 수 있는 패턴이기도 하다.
위키에서는
모델-뷰-뷰모델 - 위키백과, 우리 모두의 백과사전
모델-뷰-뷰 모델(model-view-viewmodel, MVVM)은 하나의 소프트웨어 아키텍처 패턴으로-마크업 언어 또는 GUI 코드로 구현하는-그래픽 사용자 인터페이스(뷰)의 개발을 비즈니스 로직 또는 백-엔드 로직(
ko.wikipedia.org
정리
View : 사용자에게 제공되는 UI
Model : 실제 데이터를 처리하는 구역
ViewModel : Model을 View에 표현하기 위한 중간 Model, View와 직접 바인딩되어 Model을 컨트롤하고 Model을 View에 표현하는 작업을 담당함.
사용
색상의 RGB값을 입력받고 이를 표현하는 기능을 구현해보고자 한다. 일단 예제를 만들어보자.
Model
RGBColor.cs
RGB 값을 가진 객체를 선언한다.
public class RGBColor
{
#region Properties
public byte R { get; set; }
public byte G { get; set; }
public byte B { get; set; }
#endregion
}
View
ColorView.xaml
Color를 표현하기 위한 View를 생성한다. R, G, B의 Byte값을 입력받고 입력받은 R, G, B 값을 통해 ColorText를 출력하고 출력하는 ColorText의 폰트 색상을 해당 색상으로 변경할 수 있도록 View를 제공합니다.
<UserControl x:Class="mvvm.View.ColorView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:mvvm.View" xmlns:ig="http://schemas.infragistics.com/xaml"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.Resources>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</Grid.Resources>
<TextBlock Grid.Row="0" Grid.Column="0" Text="R"/>
<TextBlock Grid.Row="1" Grid.Column="0" Text="G"/>
<TextBlock Grid.Row="2" Grid.Column="0" Text="B"/>
<TextBlock Grid.Row="3" Grid.Column="0" Text="Result"/>
<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding RValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding GValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding BValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Grid.Row="3" Grid.Column="1"
Text="{Binding ColorText, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Foreground="{Binding Color, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</UserControl>
ColorView.xaml.cs
View의 비하인드 단에는 어떠한 기능도 구현하지 않는다.
이는 ColorView.xaml의 DataContext에 ViewModel를 주입 또는 바인딩해주기 때문에 비하인드 단에서 구현할 항목은 없다. 다만 예외의 경우는 있는데, View단의 Control을 직접 다루어야 할 경우이다. MVVM 패턴의 특성상 View단의 Control을 직접 다루기 위한 방법은 두 가지가 있다.
1. ViewModel 생성자에 View 객체를 전달
2. View 비하인드 단에서 직접 조정
1번의 경우는 ViewModel과 View간의 의존성이 더 복잡해지기 때문에 추천하지 않는다.
(추후 ViewModelLocator 등을 사용할 경우, 처리가 불가함)
using System.Windows.Controls;
namespace mvvm.View
{
/// <summary>
/// ColorView.xaml에 대한 상호 작용 논리
/// </summary>
public partial class ColorView : UserControl
{
public ColorView()
{
InitializeComponent();
}
}
}
ViewModel
ColorViewModel은 Model인 RGBColor와 ColorView 간 데이터를 처리하고 UI를 표현하는 기능을 담당한다.
R, G, B값을 View로부터 입력받고 입력을 받을 때마다 이를 처리하여 ColorText, Color 값을 선정한다.
(* ReactiveUI를 사용하면 Update 함수를 Setter마다 호출하지 않아도 되는데, 이는 추후 별도로 포스팅할 예정)
public class ColorViewModel : BindableBase
{
#region Internal Field
private RGBColor _rgb;
private byte _rValue;
private byte _gValue;
private byte _bValue;
private string _colorText;
private SolidColorBrush _color;
#endregion
#region Commands
public DelegateCommand UpdateCommand { get; }
#endregion
#region Properties
public byte RValue
{
get => _rValue;
set
{
SetProperty(ref _rValue, value);
Update();
}
}
public byte GValue
{
get => _gValue;
set
{
SetProperty(ref _gValue, value);
Update();
}
}
public byte BValue
{
get => _bValue;
set
{
SetProperty(ref _bValue, value);
Update();
}
}
public string ColorText
{
get => _colorText;
set => SetProperty(ref _colorText, value);
}
public SolidColorBrush Color
{
get => _color;
set => SetProperty(ref _color, value);
}
#endregion
#region Constructor
public ColorViewModel()
{
_rgb = new RGBColor();
UpdateCommand = new DelegateCommand(Update);
}
#endregion
#region Functions
private void Update()
{
_rgb.R = _rValue;
_rgb.G = _gValue;
_rgb.B = _bValue;
var color = System.Windows.Media.Color.FromRgb(RValue, GValue, BValue);
ColorText = color.ToString();
Color = new SolidColorBrush(color);
}
#endregion
}
출력
위 코드를 실행하면 아래와 같이 출력되는 것을 확인할 수 있다.
GitHub - jaywapp/Tutorials: Tutorial Codes
Tutorial Codes. Contribute to jaywapp/Tutorials development by creating an account on GitHub.
github.com
'Software Develop > Design Pattern' 카테고리의 다른 글
싱글톤 패턴 (Singleton Pattern) (0) | 2023.01.16 |
---|---|
빌더 패턴 (Builder Pattern) (0) | 2023.01.13 |
파사드 패턴 (Facade Pattern) (0) | 2023.01.12 |
Inversion Of Control Container, IUnityContainer (0) | 2022.02.24 |
MVC 패턴 (Model - View - Contoller) (0) | 2022.02.12 |