2019년 1월 26일 토요일

WPF 데이터바인딩, 데이터컨텍스트(DataContext), Command 바인딩

WPF 데이터바인딩, 데이터컨텍스트(DataContext), Command 바인딩
n View에는 Button의 Code Behind가 포함되어 있고 ViewModel에 바인딩 되어 있는 예제이다. ViewModel 객체가 View의 DataContext로 설정되어 있으므로 View와 ViewModel의 바인딩은 단순하게 구성되어 있다.
n ViewModel의 속성 값이 변경되면 자동으로 데이터 바인딩을 통해 View로 전파되고 사용자가 View에서 Button을 클릭하면 ViewModel의 명령이 실행되어 요청한 작업을 수행한다.
1. View(MainWindow.xaml)
<Window x:Class="MVVMTest.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:MVVMTest"
mc:Ignorable="d"
Title="MainWindow" Height="150" Width="370">
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<Button Content="Click"
Height="23"
HorizontalAlignment="Left"
Margin="77,45,0,0"
Name="btnClick"
VerticalAlignment="Top"
Width="203"
Command="{Binding ButtonCommand}"
CommandParameter="Hai" />
</Grid>
</Window>
2. ViewModel(C# 클래스)- ViewModel에서 RelayCommand를 통해 메시지박스를 띄움
using System;
using System.Windows.Input;
using System.Windows;
namespace MVVMTest
{
class MainWindowViewModel
{
private ICommand m_ButtonCommand;
public ICommand ButtonCommand
{
get
{
return m_ButtonCommand;
}
set
{
m_ButtonCommand = value;
}
}
public MainWindowViewModel()
{
ButtonCommand = new RelayCommand(new Action<object>(ShowMessage));
}
public void ShowMessage(object obj)
{
MessageBox.Show(obj.ToString());
}
}
}
ICommand를 상속받은 RelayCommand.cs
using System;
using System.Windows.Input;
namespace MVVMTest
{
class RelayCommand : ICommand
{
private Action<object> _action;
public RelayCommand(Action<object> action)
{
_action = action;
}
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
if (parameter != null)
{
_action(parameter);
}
else
{
_action("Hello World");
}
}
#endregion
}
}
Command vs Click Event
- Command는 Caller와 연결되어 있지 않으므로 동일한 Command가 메뉴 항목, 도구 모음 버튼, 키보드 등에서 호출 가능
- Command는 명령 상태에 따라 관련된 모든 UI 컨트롤을 활성화 / 비활성화 할 수 있도록 지원(실행 가능 또는 불가능)

댓글 없음:

댓글 쓰기

(C#교육동영상)C# ADO.NET 실습 ODP.NET/ODAC 설치 오라클 함수 호출 실습, C#학원, WPF학원, 닷넷학원, 자바학원

  (C#교육동영상)C# ADO.NET 실습  ODP.NET/ODAC 설치  오라클 함수 호출 실습, C#학원, WPF학원, 닷넷학원, 자바학원 https://www.youtube.com/watch?v=qIPU85yAlzc&list=PLxU-i...