将字符串格式绑定到绑定



我可以将Binding内的StringFormat绑定到另一个Binding吗?

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

不能将Binding用于StringFormat。正如例外告诉您的那样,如果您尝试它:

"Binding"只能DependencyProperty设置在 DependencyObject

StringFormat不是DependencyPropertyBinding也不是DependencyObject

不过,您可以做这两件事。

  1. 将其设置为资源。

您可以在Resources中以App.xaml定义不同的字符串格式,以便在整个应用程序中可以访问它们:

<system:String x:Key="LocalCurrencyFormat">{0:C}</system:String>

system xmlns:system="clr-namespace:System;assembly=mscorlib"

然后你可以做:

<TextBlock Text="{Binding MyDouble, StringFormat={StaticResource LocalCurrencyFormat}}" />
  1. 将其设置为类的静态属性。

您可以拥有一个包含所有不同字符串格式的类:

public static class StringFormats
{
    public static string LocalCurrencyFormat
    {
        get { return "{0:C}"; }
    }
}

并通过以下方式Binding使用它:

<TextBlock Text="{Binding MyDouble, StringFormat={x:Static local:StringFormats.LocalCurrencyFormat}}" />
<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>

最新更新