Binding을 하다보면 단일 parameter가 아닌 복수 parameter를 사용해야 할 때가 있다. wpf는 이를 위해 MultiBinding이라는 것을 구현해 놓았다.
아래는 두 TextBox의 문자열을 더하는 프로그램의 예제이다.
<Window x:Class="IamNamespace.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"
mc:Ignorable="d"
xmlns:local="clr-namespace:IamNamespace"
Width="450" Height="450">
<Grid>
<StackPanel>
<TextBox x:Name="a"/>
<TextBox x:Name="b"/>
<Label>
<MultiBinding>
<MultiBinding.Bindings>
<Binding ElementName="a" Path="Text"/>
<Binding ElementName="b" Path="Text"/>
</MultiBinding.Bindings>
<MultiBinding.Converter>
<local:Class1/>
</MultiBinding.Converter>
</MultiBinding>
</Label>
</StackPanel>
</Grid>
</Window>
MultiBinding은 반드시 Converter가 필요하다. parameter가 2개 이상이면 이걸로 도대체 뭘 어쩌라는건지 컴퓨터 입장에서는 모르기 때문이다.(물론 단일 Binding도 필요하다면 Converter를 추가할 수 있다.)
Class1.cs
using System;
using System.Globalization;
using System.Windows.Data;
namespace IamNamespace
{
internal class Class1 : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values[0].ToString() + values[1].ToString();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
참고: Visual Studio를 사용한다면 IMultiValueConverter를 상속받고 밑에 빨간 줄이 쳐졌을 때 텍스트 커서를 거기에 둔 다음 Ctrl+.을 누르고 엔터를 치면 자동으로 구현해야 할 함수들을 구현해준다. 직접 해 보면 뭔 소린지 안다.
아무튼 위 프로그램을 실행하면...
실시간으로 두 문자열을 이어붙여서 Label에 나타내어지는 것을 볼 수 있다.
당연하겠지만 Binding을 추가하는 순서를 바꾸면 values의 순서도 바뀐다.
'C#' 카테고리의 다른 글
garbage collect의 함정 (0) | 2023.03.25 |
---|---|
개발자와 사용자의 관점 차이 (0) | 2023.03.14 |
인생은 살기 힘들다는데 (0) | 2023.03.08 |
Thread에서 변수 사용 주의 (0) | 2023.03.04 |
[C#] 오류를 파일에 기록해보자! (0) | 2023.02.21 |
댓글