LoginSignup
8
7

More than 5 years have passed since last update.

WPFでのMultiBindingの使用方法(TextBlockとCheckBoxで若干異なります)

Last updated at Posted at 2018-12-10

はじめに

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を使用するといいです。

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7