【问题标题】:TextBlock: Binding of Text and StringFormatTextBlock:Text和StringFormat的绑定
【发布时间】:2013-09-02 03:42:46
【问题描述】:

是否也可以绑定TextStringFormat

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

DecimalPoints 不断地从 F0 变为 F15。不幸的是,上面的代码无法编译。

【问题讨论】:

  • 不,但您可以使用转换器来完成此操作

标签: wpf xaml binding textblock string-formatting


【解决方案1】:

我认为您最好的选择绝对是转换器。然后您的绑定将如下所示:

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

【讨论】:

  • 完美运行,谢谢。 “让它变得更好”是什么意思?
  • 好吧,例如,我假设传递的值是双精度和整数。另外我假设传递了两个值(而不是说 - 只有一个)。您可以通过首先检查参数来使该方法更加简单。
  • @Liz,您能否检查一下我的问题:stackoverflow.com/questions/40134370/…
【解决方案2】:

如@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

【讨论】:

    【解决方案3】:

    不,你不能......原因是因为你只能绑定到 DependencyObjectDependencyPropertyBinding 类的 StringFormat 属性只是 string

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 2011-08-17
      • 2011-05-22
      • 2019-01-27
      • 2014-10-04
      • 2011-03-11
      相关资源
      最近更新 更多