5

我寫了一段代碼,用c#代碼創建自己的DataTemplate。我將它添加到datagrid列的編輯模板中。 當我調用object templateContent = tc.CellTemplate.LoadContent ();時,應用程序崩潰了,並且拋出了一個異常,它是「FrameworkElementFactory必須位於此操作的密封模板中」。 這是我創建我的數據模板的代碼。FrameworkElementFactory必須在此操作的密封模板中

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

回答

13

我反映了反射器中的框架模板代碼。我發現tc.CellTemplate.LoadContent()涉及類FrameworkTemplate中名爲「_sealed」的專用字段。

然後我找到了設置值的字段,我打電話給這個方法,問題就解決了。

這裏是解決方案:

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

你搖滾!謝謝! – Marc

+2

我一直在使用Telerik GridView動態地創建DataTemplates,並且必須調用Seal()才能使其工作。你知道爲什麼嗎?我無法找到爲什麼應該使用這個的任何例子? –

相關問題