FrameworkElementFactory must be in a sealed template for this operation
Asked Answered
S

1

9

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;
    }
Susysuter answered 8/8, 2011 at 9:17 Comment(0)
S
24

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;
}
Susysuter answered 9/8, 2011 at 1:46 Comment(1)
I've been creating DataTemplates dynamically using a Telerik GridView and had to call Seal() to get it work. Do you know why? I couldn't find any examples of why this should be used?Sou

© 2022 - 2024 — McMap. All rights reserved.