天天看點

WPF在代碼中建立DataTemplate時候的異常

原文:

WPF在代碼中建立DataTemplate時候的異常

今天寫段程式用到了在代碼中手動建立DataTemplate,

    var factory = new FrameworkElementFactory(typeof(OperationColumn));

    return

new

DataTemplate() { VisualTree = factory };

運作的時候出現如下異常: FrameworkElementFactory 必須位于此操作的密封模闆中。

在 System.Windows.FrameworkElementFactory.InstantiateUnoptimizedTree()

在 System.Windows.FrameworkTemplate.LoadContent()

  

WPF在代碼中建立DataTemplate時候的異常

平時我也是這麼些的,一直都是好好的,不知道這次是不是用了一個第三方控件的緣故。網上搜了一下,後在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;