2015-06-24 21 views
1

当我有以下代码的背后崩溃:WPF的DataTemplate在代码设置length属性

protected override DataTemplate _CreateDataTemplate() 
    { 
     DataTemplate dataTemplate = new DataTemplate(); 
     FrameworkElementFactory 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不是属性宽度有效的值”。

当我没有设置图像的宽度一切工作正常。不幸的是,宽度非常重要。

对不起,糟糕的代码格式,我没有找到如何使之完全格式化。

+0

“崩溃”?抛出什么异常? – Herdo

+0

15不是财产宽度 –

回答

4

FrameworkElement.Width属性类型为double,但您试图将其设置为整数值。

相反,把它写像下面的一个:

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

感谢的人你是神的有效值:d –

+0

@HansDabi我增加了更多的例子给你。请看看MSDN“double”页面的链接。 – Herdo

+0

如果它解决了你的问题,它应该起码投票。 – Ahmad

相关问题