我可以将Binding
内的StringFormat
绑定到另一个Binding
吗?
Text="{Binding DeficitDollars, StringFormat={0:E6}}"
Text="{Binding GNP, StringFormat={Binding LocalCurrencyFormat}}"
不能将Binding
用于StringFormat
。正如例外告诉您的那样,如果您尝试它:
"
Binding
"只能DependencyProperty
设置在DependencyObject
StringFormat
不是DependencyProperty
,Binding
也不是DependencyObject
。
不过,您可以做这两件事。
- 将其设置为资源。
您可以在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}}" />
- 将其设置为类的静态属性。
您可以拥有一个包含所有不同字符串格式的类:
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>