Binding中的WPF StringFormat在后面的代码中不起作用

时间:2017-01-09 19:37:02

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

我正在尝试在代码隐藏中以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);

1 个答案:

答案 0 :(得分: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情况下转换为字符串,否则返回double值原样。 Convert会返回object,因此没问题。

为简单起见,以下代码假定您可以依靠value始终为double

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