(동영상)WPF DataBinding, IValueConverter를 이용한 데이터바인딩
n 데이터바인딩시 소스와 타겟의 데이터 타입이 다른 경우가 는데, 예를 들면 체크박스의 체크여부에 따라 “예”, “아니오” 등을 표시하는 경우 등이 있습니다.
n 데이터바인딩시 타입의 변경을 위해서 IValueConverter를 사용하며 IValueConverter 인터페이스를 구현하는 클래스가 소스와 타겟 사이의 값을 변환 합니다.
n WPF Value Converter는 IValueConverter 인터페이스 또는 IMultiValueConverter 인터페이스를 구현해야 하며 Convert() 및 ConvertBack()의 두 가지 메서드만 구현하면 됩니다.
n 문자열을 입력으로 불리언(Boolean) 값을 반환하는 간단한 변환기를 구현해 보겠습니다.
n [실행화면]
n [YesNoToBoolConverter.cs]
using System;
using System.Windows.Data;
namespace WpfApp12
{
class YesNoToBoolConverter : IValueConverter
{
// 소스값이 타겟에 바인딩 되는 경우 호출
// TextBox à TextBlock, TextBox à CheckBox
// TextBox의 Text속성의 값 "YES", "NO"에 따리 true, false를 리턴
public object Convert(object value, Type targetType, object param, System.Globalization.CultureInfo culture)
{
switch (value.ToString().ToUpper())
{
case "YES": return true;
case "NO": return false;
}
return false;
}
// 타겟값이 역으로 소스에 바인딩 될때 호출
// CheckBox --> TextBox
// CheckBox의 값 true, false에 따라 "YES", "NO" 문자열을 리턴
public object ConvertBack(object value, Type targetType, object param, System.Globalization.CultureInfo culture)
{
if (value is bool)
{
if ((bool)value == true) return "YES";
else return "NO";
}
return "NO";
}
}
}
n [MainWindow.xaml]
<Window x:Class="ConverterTest.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:ConverterTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<local:YesNoToBoolConverter x:Key="converter"/>
</Window.Resources>
<StackPanel>
<TextBox Name="txtValue" Text="YES"/>
<WrapPanel>
<TextBlock Text="Current Value : "/>
<TextBlock Text="{Binding ElementName=txtValue, Path=Text, Converter={StaticResource converter}}"/>
</WrapPanel>
<CheckBox Content="Yes" IsChecked="{Binding ElementName=txtValue, Path=Text, Converter={StaticResource converter}}" />
</StackPanel>
</Window>