LoginSignup
37
52

More than 5 years have passed since last update.

[WPF] XAMLでの文字列のフォーマット指定とバインディング

Last updated at Posted at 2017-05-31

WPFでのデータを使用した文字列の指定はViewModel側で文字列まで加工する必要があるかと思っていたけれども、実はXAML側で指定できたのでやりかたメモ

基本

以下のように StringFormat を使用します。

基本
<TextBlock Text="{Binding Value, StringFormat={}{0} 円}"/>
<TextBlock Text="{Binding Value, StringFormat=商品A {0} 円}"/>

バインディングするデータが最初に来る場合は、頭に {} を付ける必要があります。(属性値のBindingなどではなく文字として中括弧がつかいたいため)

書式指定

StringFormat内では書式指定ができます。(例:数字の0埋めなど)

3桁の0埋め
<TextBlock Text="{Binding Value, StringFormat=商品A {0:D3} 円}"/>

指定方法は以下などを参照してください

マルチバインディング

一つの文字列に複数のデータをバインディングしたい場合は以下のようにします。
MultiBindingの指定でもデータが最初に来る場合は頭に {} をつける必要があります。

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="First {0} : Second {1}">
            <Binding Path="FirstValue"/>
            <Binding Path="SecondValue"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

string以外の型から文字列を取得したい場合はConverterを使いますが、
Converterも以下のようにして使用できます

<Binding Path="Value" Converter="{StaticResource SomethingConverter}"/>

MultiBinding クラス (System.Windows.Data)
Binding クラス (System.Windows.Data)

参考

BindingBase.StringFormat プロパティ (System.Windows.Data)
.NET Framework における型の書式設定

Nine Works WPFのStringFormatによるフォーマット指定

37
52
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
37
52