Is it possible to bind Text
and StringFormat
too?
<TextBlock Text="{Binding Path=Price, StringFormat={Binding Path=DecimalPoints}}" />
DecimalPoints is constantly changing from F0
to F15
. Unfortunatelly the code above doesn't compile.
Is it possible to bind Text
and StringFormat
too?
<TextBlock Text="{Binding Path=Price, StringFormat={Binding Path=DecimalPoints}}" />
DecimalPoints is constantly changing from F0
to F15
. Unfortunatelly the code above doesn't compile.
我认为您最好的选择绝对是转换器。然后您的绑定将如下所示:
<TextBlock.Text>
<MultiBinding Converter="{StaticResource StringFormatConverter }">
<Binding Path="Price"/>
<Binding Path="DecimalPoints"/>
</MultiBinding>
</TextBlock.Text>
然后是一个快速转换器(你当然可以让它更好,但这是一般的想法)。
public class StringFormatConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double number = (double)values[0];
string format = "f" + ((int)values[1]).ToString();
return number.ToString(format);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
正如@Sheridan 提到的,在这种情况下,Binding
将不起作用。但是您可以使用静态字符串创建一个类,并在 XAML 中引用它们。语法是:
<x:Static Member="prefix : typeName . staticMemberName" .../>
下面是一个例子:
XAML
xmlns:local="clr-namespace:YourNameSpace"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
<Grid>
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, StringFormat={x:Static Member=local:StringFormats.DateFormat}}"
HorizontalAlignment="Right" />
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, StringFormat={x:Static Member=local:StringFormats.Time}}" />
</Grid>
Code behind
public class StringFormats
{
public static string DateFormat = "Date: {0:dddd}";
public static string Time = "Time: {0:HH:mm}";
}
欲了解更多信息,请参阅:
不,你不能......原因是因为你只能绑定到 aDependencyProperty
并且DependencyObject
类的StringFormat
属性Binding
只是 a string
。