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

标签 c# wpf datatemplate

我有以下代码:

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/

相关文章:

wpf - 如何停止在特定条件下创建模板

c# - 使用 C# 运行 T4 模板

c# - 阻止 Ninject 自动绑定(bind) Func<T, T, bool>

c# - 如何在 xamarin 表单中设置 MasterDetailPage 的宽度

c# - 无法更改DataGrid中的前景

WPF DataTemplate 事件绑定(bind)到对象函数

wpf - 任何人都知道如何从使用 DataTemplate 作为其列表框项的 WPF 列表框中删除默认突出显示颜色?

c# - C# 中的蓝牙,哪个堆栈,哪个 SDK?

c# - WPF C# 触摸滚动正在拖动整个窗口

c# - 关闭窗口返回结果