WPF: ラベルの StringFormat の問題 質問する

WPF: ラベルの StringFormat の問題 質問する

以下のバージョンは期待どおりに動作します:

<DataGridTextColumn Header="Total Units" Binding="{Binding TotalUnits, Mode=OneWay, StringFormat=N0}"/>

<TextBlock Text="{Binding TotalUnits, Mode=OneWay, StringFormat=N0}"/>

ラベルで試してみると、StringFormat が無視され、「123」ではなく「123.000000」が返されます。

<Label Content="{Binding TotalUnits, Mode=OneWay, StringFormat=N0}"/>

TotalUnits は小数です。

どうしたの?

ベストアンサー1

プロパティを持つものには、Binding で StringFormat を指定するのではなく、使用する必要があるContent特別なプロパティがあります。ContentStringFormat

このような:

<Window.Resources xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <sys:Int16 x:Key="MyValue">100</sys:Int16>
</Window.Resources>

<StackPanel DataContext="{StaticResource MyValue}">

    <!-- using Label -->
    <Label Content="{Binding}" ContentStringFormat="{}{0:C}" />

    <!-- using TextBlock-->
    <TextBlock Text="{Binding, StringFormat={0:C}}" />

</StackPanel>

おすすめ記事