TOC

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

데이터 바인딩:

The StringFormat property

앞 장에서 본 것처럼, Converter를 사용해 바인딩 표시 전 결과를 조작할 수 있습니다. Converter의 장점은 모든 데이터 타입을 완전히 다른 데이터 타입으로 변경할 수 있다는 것입니다. 그러나 특정 값이 표시되는 방식만 변경하고 다른 유형으로 변환할 필요가 없는 경우, StringFormat 프로퍼티를 사용해서 충분히 할 수 있습니다.

바인딩의 StringFormat 프로퍼티를 사용하면 converter를 사용할 때 얻을 수 있는 유연성이 다소 떨어지지만, 사용이 훨씬 간편하고 새 파일에 새 클래스를 만들 필요가 없습니다.

StringFormat 프로퍼티는 이름처럼 String.Format 함수를 호출해서 출력 문자열 포맷을 만듭니다. 백문불여일견이니 바로 예제를 보겠습니다.

<Window x:Class="WpfTutorialSamples.DataBinding.StringFormatSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
		xmlns:system="clr-namespace:System;assembly=mscorlib"
        Title="StringFormatSample" Height="150" Width="250"
		Name="wnd">
	<StackPanel Margin="10">
		<TextBlock Text="{Binding ElementName=wnd, Path=ActualWidth, StringFormat=Window width: {0:#,#.0}}" />
		<TextBlock Text="{Binding ElementName=wnd, Path=ActualHeight, StringFormat=Window height: {0:C}}" />
		<TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, StringFormat=Date: {0:dddd, MMMM dd}}" />
		<TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, StringFormat=Time: {0:HH:mm}}" />
	</StackPanel>
</Window>

TextBlock의 첫 번째 커플은 부모 Window에 바인딩하고 너비와 높이를 가져와서 값을 가져옵니다. StringFormat 속성을 통해 값이 형식화됩니다. 너비의 경우 사용자 지정 형식 지정 문자열을 지정하고 높이의 경우 재미를 위해 통화 형식을 사용하도록 요청합니다. value는 double 형식으로 저장되므로 double.ToString()을 호출한 것처럼 동일한 형식 지정자를 모두 사용할 수 있습니다. 여기에서 목록을 찾을 수 있습니다.: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

또한 StringFormat 내에 커스텀 텍스트를 포함시킬 수 있다는 것을 눈여겨 보십시오. 원하는 텍스트를 값의 앞과 뒤에 붙일 수 있습니다. format string 내부에 실제 값을 참조할 때, 중괄호 안에 2개의 값, 즉 포맷팅하기 원하는 값의 참조(가능한 첫 값으로서 숫자 0)와 포맷 문자열을 콜론으로 나누어 포함합니다:

마지막 두 값의 경우 현재 날짜(DateTime.Now)에 바인딩하고 먼저 특정 형식의 날짜로 출력한 다음 시간(시간 및 분)으로 출력합니다. (시간 및 분)으로 출력하고, 다시 사전 정의된 자체 형식을 사용합니다. 날짜/시간 서식에 대한 자세한 내용은 여기에서 확인할 수 있습니다: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

추가 텍스트 없이 서식 지정

위의 모든 예에서와 같이 사용자 지정 텍스트가 포함되지 않은 형식 문자열을 지정하는 경우 XAML에서 정의할 때 추가 중괄호 집합을 추가해야 합니다. 그 이유는 WPF가 구문을 마크업 확장에 사용되는 구문과 혼동할 수 있기 때문입니다. 다음은 예입니다.

<Window x:Class="WpfTutorialSamples.DataBinding.StringFormatSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
		xmlns:system="clr-namespace:System;assembly=mscorlib"
        Title="StringFormatSample" Height="150" Width="250"
		Name="wnd">
	<WrapPanel Margin="10">
		<TextBlock Text="Width: " />
		<TextBlock Text="{Binding ElementName=wnd, Path=ActualWidth, StringFormat={}{0:#,#.0}}" />
	</WrapPanel>
</Window>

특정 컬처 사용

특정 컬처에 따라 바인딩된 값을 출력해야 하는 경우에도 문제 없습니다. 바인딩은 부모 요소에 지정된 언어를 사용하거나 요소에 지정된 언어를 사용하거나 ConverterCulture 속성을 사용하여 바인딩에 직접 지정할 수 있습니다. 다음은 예시입니다:

<Window x:Class="WpfTutorialSamples.DataBinding.StringFormatCultureSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
		xmlns:system="clr-namespace:System;assembly=mscorlib"
        Title="StringFormatCultureSample" Height="120" Width="300">
	<StackPanel Margin="10">
		<TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, ConverterCulture='de-DE', StringFormat=German date: {0:D}}" />
		<TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, ConverterCulture='en-US', StringFormat=American date: {0:D}}" />
		<TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, ConverterCulture='ja-JP', StringFormat=Japanese date: {0:D}}" />
	</StackPanel>
</Window>

매우 간단합니다: D 지정자(긴 날짜 패턴)를 사용하는 StringFormat 속성과 ConverterCulture 속성을 결합하면 특정 culture에 따라 바인딩된 값을 출력할 수 있습니다. 꽤 멋지죠!


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!
Table of Contents