Andyz Smith
Andyz Smith

Reputation: 708

Binding StringFormat to a binding

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

Answers (2)

J. Hasan
J. Hasan

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

Szabolcs D&#233;zsi
Szabolcs D&#233;zsi

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 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}}" />

Upvotes: 1

Related Questions