TOC

This article is currently in the process of being translated into Korean (~22% done).

데이터 바인딩:

Value conversion with IValueConverter

지금까지는 데이터 바인딩을 하는 대상끼리 호환되는 속성을 사용했습니다. 하지만 호환되지 않는 데이터를 바인딩 시켜야 할 경우가 생길 것입니다. 한 가지 유형의 값을 다른 방식으로 표현하는 경우를 살펴보겠습니다.

When to use a value converter

값 변환기는 데이터 바인딩을 할 때 자주 사용될 것입니다. 간단한 예는 다음과 같습니다.

  • 숫자 값 0을 한 가지 방법으로, 양수 하나를 다른 방법으로 표시하려고 합니다.
  • 체크박스를 값으로 확인하려는데 값이 Boolean 값이 아니라 "yes", "no" 처럼 문자열 형식인 경우입니다.
  • 파일 크가는 바이트 단위이지만 파일의 크기에 따라 바이트, 킬로바이트, 메가바이트, 기가바이트 단위로 나누어 표시하려고 합니다.

위의 경우는 간단한 경우입니다. 하지만 훨씬 더 많은 사용법이 있습니다. 예를 들어 true/false를 기준으로 체크박스를 선택/해제하려고 하는데 true일 경우 체크박스를 해제하는 경우와 같이 값을 반전시킬 수도 있습니다. 또한 변환기를 사용하여 true일 경우 초록불, false일 경우 빨간불을 표시하는 등 값을 기반으로 이미지를 표시할 수도 있습니다. 가능성은 무한합니다!

이처럼 값 변환기를 유용하게 사용할 수 있습니다. IValueConverter 인터페이스를 사용하는 이 클래스는 마치 번역가처럼 소스와 바인딩 대상 사이에서 값을 변환시켜줍니다. 즉, 값을 대상에 적용하거나 소스에 대입할 때 변환이 필요한 경우 변환기가 필요할 것입니다.

Implementing a simple value converter

As mentioned, a WPF value converter needs to implement the IValueConverter interface, or alternatively, the IMultiValueConverter interface (more about that one later). Both interfaces just requires you to implement two methods: Convert() and ConvertBack(). As the name implies, these methods will be used to convert the value to the destination format and then back again.

Let's implement a simple converter which takes a string as input and then returns a Boolean value, as well as the other way around. If you're new to WPF, and you likely are since you're reading this tutorial, then you might not know all of the concepts used in the example, but don't worry, they will all be explained after the code listings:

<Window x:Class="WpfTutorialSamples.DataBinding.ConverterSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
		xmlns:local="clr-namespace:WpfTutorialSamples.DataBinding"
        Title="ConverterSample" Height="140" Width="250">
	<Window.Resources>
		<local:YesNoToBooleanConverter x:Key="YesNoToBooleanConverter" />
	</Window.Resources>
	<StackPanel Margin="10">
		<TextBox Name="txtValue" />
		<WrapPanel Margin="0,10">
			<TextBlock Text="Current value is: " />
			<TextBlock Text="{Binding ElementName=txtValue, Path=Text, Converter={StaticResource YesNoToBooleanConverter}}"></TextBlock>
		</WrapPanel>
		<CheckBox IsChecked="{Binding ElementName=txtValue, Path=Text, Converter={StaticResource YesNoToBooleanConverter}}" Content="Yes" />
	</StackPanel>
</Window>
using System;
using System.Windows;
using System.Windows.Data;

namespace WpfTutorialSamples.DataBinding
{
	public partial class ConverterSample : Window
	{
		public ConverterSample()
		{
			InitializeComponent();
		}
	}

	public class YesNoToBooleanConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			switch(value.ToString().ToLower())
			{
				case "yes":
				case "oui":
					return true;
				case "no":
				case "non":
					return false;
			}
			return false;
		}

		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			if(value is bool)
			{
				if((bool)value == true)
					return "yes";
				else
					return "no";
			}
			return "no";
		}
	}
}

Code-behind

So, let's start from the back and then work our way through the example. We have implemented a converter in the Code-behind file called YesNoToBooleanConverter. As advertised, it just implements the two required methods, called Convert() and ConvertBack(). The Convert() methods assumes that it receives a string as the input (the value parameter) and then converts it to a Boolean true or false value, with a fallback value of false. For fun, I added the possibility to do this conversion from French words as well.

The ConvertBack() method obviously does the opposite: It assumes an input value with a Boolean type and then returns the English word "yes" or "no" in return, with a fallback value of "no".

You may wonder about the additional parameters that these two methods take, but they're not needed in this example. We'll use them in one of the next chapters, where they will be explained.

XAML

In the XAML part of the program, we start off by declaring an instance of our converter as a resource for the window. We then have a TextBox, a couple of TextBlocks and a CheckBox control and this is where the interesting things are happening: We bind the value of the TextBox to the TextBlock and the CheckBox control and using the Converter property and our own converter reference, we juggle the values back and forth between a string and a Boolean value, depending on what's needed.

If you try to run this example, you will be able to change the value in two places: By writing "yes" in the TextBox (or any other value, if you want false) or by checking the CheckBox. No matter what you do, the change will be reflected in the other control as well as in the TextBlock.

Summary

This was an example of a simple value converter, made a bit longer than needed for illustrational purposes. In the next chapter we'll look into a more advanced example, but before you go out and write your own converter, you might want to check if WPF already includes one for the purpose. As of writing, there are more than 20 built-in converters that you may take advantage of, but you need to know their name. I found the following list which might come in handy for you: http://stackoverflow.com/questions/505397/built-in-wpf-ivalueconverters

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!