Reputation: 708
Can I bind StringFormat
inside a Binding
to another Binding
?
Text="{Binding DeficitDollars, StringFormat=\{0:E6\}}"
Text="{Binding GNP, StringFormat={Binding LocalCurrencyFormat}}"
Upvotes: 0
Views: 231
Reputation: 512
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Width="500" Height="500">
<Window.Resources>
<sys:String x:Key="LocalCurrencyFormat">Total: {0:C}</sys:String>
</Window.Resources>
<StackPanel>
<TextBlock Text="{Binding DeficitDollars, StringFormat=\{0:E6\}}"></TextBlock>
<TextBlock Text="{Binding Path=GNP, StringFormat={StaticResource LocalCurrencyFormat}}" />
</StackPanel>
</Window>
Upvotes: 0
Reputation: 8843
You can't use a Binding
for StringFormat
. As the exception tells you if you try it:
A '
Binding
' can only be set on aDependencyProperty
of aDependencyObject
StringFormat
is not a DependencyProperty
and Binding
is not a DependencyObject
.
You can do these two things though.
You can define your different string formats in App.xaml
in the Resources
so they'll be reachable in the whole application:
<system:String x:Key="LocalCurrencyFormat">{0:C}</system:String>
system
is xmlns:system="clr-namespace:System;assembly=mscorlib"
And then you can do:
<TextBlock Text="{Binding MyDouble, StringFormat={StaticResource LocalCurrencyFormat}}" />
You can have a class with all your different string formats:
public static class StringFormats
{
public static string LocalCurrencyFormat
{
get { return "{0:C}"; }
}
}
And use it in the Binding
the following way:
<TextBlock Text="{Binding MyDouble, StringFormat={x:Static local:StringFormats.LocalCurrencyFormat}}" />
Upvotes: 1