はじめに
WPF(C#)でMultiBindingで、複数の値をバインディングする方法についてまとめています。
TL;TD
プロパティがTextの場合は、StringFormatが利用できます。
プロパティがContextの場合は、StringFormatが利用できないので、Converterを介する必要があります。
コード
- TextBlockの場合はStringFormatで表示ができます。
- 最初にBindingの値を表示する場合は、「{}」を記載しておく必要があります。
sample1.xaml
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{} {0}:{1}">
<Binding path={name}/>
<Binding path={kind_name}/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
- CheckBoxの場合はStringFormatが利用できないので、Converterを介して表示する
sample2.xaml
<CheckBox>
<CheckBox.Text>
<MultiBinding StringFormat="{StaticResource hogeConverter}">
<Binding path={name}/>
<Binding path={kind_name}/>
</MultiBinding>
</CheckBox.Text>
</CheckBox>
hogeConverter.cs
public class hogeConverter : IMultiConverter {
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return string.Format("{0}:{1}", values[0], values[1]);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
まとめ
StringFormatが利用できるときは利用して、利用できないときはConverterを使用するといいです。