我有以下代码:
protected override DataTemplate _CreateDataTemplate()
{
var dataTemplate = new DataTemplate();
var factory = new FrameworkElementFactory(typeof(DockPanel));
factory.SetBinding(Panel.BackgroundProperty, new Binding(CellContentBindingPath.Replace(".ValueUser", ".Background")));
dataTemplate.VisualTree = factory;
var childFactory = new FrameworkElementFactory(typeof(Image));
childFactory.SetValue(FrameworkElement.WidthProperty, 15);
factory.AppendChild(childFactory);
childFactory = new FrameworkElementFactory(typeof(TextBlock));
factory.AppendChild(new FrameworkElementFactory(""));
childFactory.SetBinding(TextBlock.TextProperty, !ShowZero ? new Binding(CellContentBindingPath) { Converter = new ValueToNothingConverter() } : new Binding(CellContentBindingPath));
childFactory.SetValue(FrameworkElement.HorizontalAlignmentProperty, ContentAlignment);
factory.AppendChild(childFactory);
return dataTemplate;
}
错误是“15 不是属性宽度的有效值”。
当我不设置图像的宽度时,一切正常。不幸的是,宽度非常重要。
对于错误的代码格式,我深表歉意,我没有找到如何使其格式正确的方法。
最佳答案
FrameworkElement.Width
属性类型为 double ,但您正试图将其设置为一个整数值。
相反,将其写成以下之一:
childFactory.SetValue(FrameworkElement.WidthProperty, 15.0);
childFactory.SetValue(FrameworkElement.WidthProperty, 15d);
childFactory.SetValue(FrameworkElement.WidthProperty, 15D);
关于c# - 设置宽度属性时代码隐藏中的 WPF DataTemplate 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31020358/