7

我编写了一个片段来通过 c# 代码创建自己的 DataTemplate。我将它添加到 datagrid 列的编辑模板中。当我打电话object templateContent = tc.CellTemplate.LoadContent ( );时,应用程序崩溃了,并向我抛出了一个异常,即“FrameworkElementFactory 必须位于此操作的密封模板中。”。这是我创建数据模板的代码。

public override DataTemplate GenerateCellTemplate ( string propertyName )
    {
        DataTemplate template = new DataTemplate ( );
        var textBlockName = string.Format ( "{0}_TextBlock", propertyName );
        FrameworkElementFactory textBoxElement = new FrameworkElementFactory ( typeof ( TextBlock ), textBlockName );
        textBoxElement.SetBinding ( TextBlock.TextProperty, new Binding ( propertyName ) );
        template.VisualTree = textBoxElement;
        Trigger trigger = new Trigger ( );
        return template;
    }
4

1 回答 1

20

我在反射器中反映框架模板代码。而且我发现 tc.CellTemplate.LoadContent () 与 FrameworkTemplate 类中名为“_sealed”的私有字段有关。

然后我找到了设置值的字段,我调用了这个方法,问题就解决了。

这是解决方案:

public override DataTemplate GenerateCellTemplate ( string propertyName )
{
    DataTemplate template = new DataTemplate ( );
    var textBlockName = string.Format ( "{0}_TextBlock", propertyName );
    FrameworkElementFactory textBoxElement = new FrameworkElementFactory ( typeof ( TextBlock ), textBlockName );
    textBoxElement.SetBinding ( TextBlock.TextProperty, new Binding ( propertyName ) );
    template.VisualTree = textBoxElement;
    Trigger trigger = new Trigger ( );

    // This solves it!
    template.Seal();

    return template;
}
于 2011-08-09T01:46:39.637 回答