WPF DataTemplate in Code Behind crashes when setting width property

2.2k Views Asked by At

I have following Code:

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;
}

The Error is "15 is not a valid value for property width".

When I don't set the width of the image everything works fine. Unfortunately the width is pretty important.

Sorry for the bad code formatting, I didn't found out how to make it well formatted.

1

There are 1 best solutions below

2
On BEST ANSWER

The FrameworkElement.Width property is of type double, but you're trying to set it to an integer value.

Instead, write it like one of the following:

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