wpfexceptiondatatemplatewpfdatagridframeworkelementfactory

FrameworkElementFactory must be in a sealed template for this operation


I wrote a snippet to create a own DataTemplate by c# code. And i add it to datagrid column's editing template. When i called object templateContent = tc.CellTemplate.LoadContent ( );, the application crashed, and throw me a exception which is "FrameworkElementFactory must be in a sealed template for this operation.". This is the code i create my datatemplate.

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

Solution

  • I reflect the framework template code in reflector. And i found tc.CellTemplate.LoadContent ( ) is concerned with a private field named "_sealed" in the class FrameworkTemplate.

    Then i found the field where be set value, and i call this method, the problem is solved.

    Here is the solution:

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