【问题标题】:WPF StringFormat in Binding doesn't work in code behindBinding 中的 WPF StringFormat 在后面的代码中不起作用
【发布时间】:2017-05-24 03:52:17
【问题描述】:

我正在尝试在代码隐藏中以编程方式 100% 创建一个 DataTemplate。一切正常,除了文本块中文本绑定上的 StringFormat 不起作用。

通常在 xaml 中,我会这样做:

<TextBlock Text={Binding MyProperty, StringFormat=0.0} />

所以我假设我可以设置 Binding 对象的 StringFormat 属性,我确实这样做了。我验证它设置正确,确实如此,但我的视图仍然没有反映格式。为什么?

这是我的代码的摘录:一个为我动态创建 DataTemplate 的函数。从字面上看,从设置绑定路径到 ivalue 转换器,一切都完美无缺。只是不是字符串格式。

string propertyName = "myPropertyName";
FrameworkElementFactory textBlock = new FrameworkElementFactory(typeof(TextBlock));

// the property I want is owned by myObject, which is a property of the datacontext
string bindingString = String.Format("myObject[{0}]", propertyName); 
Binding binding = new Binding(bindingString)
{
    Mode = BindingMode.OneWay,
    Converter = (IValueConverter)Application.Current.FindResource("InvalidValuesConverter"),
    StringFormat = "{0:F1}" // <-- Here is where I specify the stringFormat. I've also tried "0.0"
};

textBlock.SetBinding(TextBlock.TextProperty, binding);

【问题讨论】:

  • MCVE 是你最好的朋友。因为到目前为止一切似乎都是probably correct,但没有使用实际的类型和格式字符串以及一大堆不相关的代码,很难确定。
  • 编辑删除不必要的代码
  • 后面代码中的Binding有一个Converter,因此忽略了StringFormat。
  • @Clemens 我测试过,发现并非如此。
  • @EdPlunkett 您的转换器是否返回字符串?

标签: c# wpf data-binding string-formatting datatemplate


【解决方案1】:

看起来您看到的是正在应用StringFormat,但它不会对您的转换器返回的字符串值进行数字格式设置。由于您使用的特定格式只有数字格式,因此实际上转换器 + StringFormat 处理在非 NaN 情况下是无操作的。测试这个假设的最快方法是给它一个像N={0:#} 这样的格式,我就是这么做的。它将十进制3.5 格式化为"N=4",将字符串"3.5" 格式化为"N=3.5"

当然,values are passed through the converter before they're formatted.

由于您的转换器的唯一目的是将空字符串替换为 Double.NaN,我建议您的转换器仅在 NaN 情况下转换为字符串,否则按原样返回双精度值。 Convert 返回 object 所以没问题。

为简单起见,下面的代码假定您可以指望value 始终为double

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (double.IsNaN((double)value)) 
            ? "" 
            : value;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多