TextBlock:Text和StringFormat的绑定

时间:2013-08-29 15:47:04

标签: wpf xaml binding textblock string-formatting

是否可以绑定TextStringFormat

<TextBlock Text="{Binding Path=Price, StringFormat={Binding Path=DecimalPoints}}" />

小数点不断从F0更改为F15。不幸的是,上面的代码无法编译。

3 个答案:

答案 0 :(得分:5)

正如@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}";
}   

有关详细信息,请参阅:

x:Static Markup Extension on MSDN

答案 1 :(得分:5)

我认为你最好的选择绝对是转换器。然后你的绑定看起来像这样:

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

答案 2 :(得分:3)

不,你不能......原因是因为你只能绑定DependencyProperty的{​​{1}}而DependencyObject类的StringFormat属性是只需Binding

相关问题