0

Can I bind StringFormat inside a Binding to another Binding?

Text="{Binding DeficitDollars, StringFormat=\{0:E6\}}"

Text="{Binding GNP, StringFormat={Binding LocalCurrencyFormat}}"
Szabolcs Dézsi
  • 8,743
  • 21
  • 29
Andyz Smith
  • 698
  • 5
  • 20

2 Answers2

1

You can't use a Binding for StringFormat. As the exception tells you if you try it:

A 'Binding' can only be set on a DependencyProperty of a DependencyObject

StringFormat is not a DependencyProperty and Binding is not a DependencyObject.

You can do these two things though.

  1. Setting it to a resource.

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}}" />
  1. Setting it to a static property of a class.

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}}" />
Szabolcs Dézsi
  • 8,743
  • 21
  • 29
  • These are good patterns. I was really looking for something more dynamic, where I could define the Formats in a Template and then pass info from my End-User XAML page into the template and there would be some logic. I Think I can put that logic instead into a Converter in the Template. Right now, App.xaml is sufficient, but I certainly see that becoming a maintenance nightmare as it becomes a clearinghouse for thousands of build-specific configuration parameters. I'd rather tie to and have more dynamic capabilities of - the {Binding}- to a Class or Template-Class or User-Control property. – Andyz Smith Jan 31 '16 at 15:03
0
<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>
J. Hasan
  • 492
  • 3
  • 14