【发布时间】: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