开发者

FrameworkElementFactory must be in a sealed template for this operation

开发者 https://www.devze.com 2023-03-26 08:57 出处:网络
I wrote a snippet to create a own DataTemplate by c# code. And i add it to datagrid column\'s editing template.

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 ) );
        templa开发者_运维技巧te.VisualTree = textBoxElement;
        Trigger trigger = new Trigger ( );
        return template;
    }


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

精彩评论

暂无评论...
验证码 换一张
取 消