代码隐藏中的 WPF DataTemplate 在设置宽度时崩溃 属性

WPF DataTemplate in Code Behind crashes when setting width property

我有以下代码:

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 property is of type double,但您试图将其设置为 整数 值。

相反,将其写成以下之一:

childFactory.SetValue(FrameworkElement.WidthProperty, 15.0);
childFactory.SetValue(FrameworkElement.WidthProperty, 15d);
childFactory.SetValue(FrameworkElement.WidthProperty, 15D);