WPF在代码中创建DataTemplate时候的异常

今天写段程序用到了在代码中手动创建DataTemplate,

    var factory = new FrameworkElementFactory(typeof(OperationColumn));
    return new DataTemplate() { VisualTree = factory };

运行的时候出现如下异常: FrameworkElementFactory 必须位于此操作的密封模板中。

在 System.Windows.FrameworkElementFactory.InstantiateUnoptimizedTree()
在 System.Windows.FrameworkTemplate.LoadContent()

  

平时我也是这么些的,一直都是好好的,不知道这次是不是用了一个第三方控件的缘故。网上搜了一下,后在StackOverFlow上找到了解决方案: FrameworkElementFactory must be in a sealed template for this operation

具体的做法是:创建了DataTemplate后,调用Seal函数锁定模板。

    var factory = new FrameworkElementFactory(typeof(OperationColumn));
    var dataTemplate = new DataTemplate() { VisualTree = factory };
    
dataTemplate.Seal();
    return dataTemplate;

原文地址:https://www.cnblogs.com/TianFang/p/3695326.html