我用c#代码编写了一段代码来创建自己的DataTemplate。并将其添加到datagrid列的编辑模板中。当我调用object templateContent = tc.CellTemplate.LoadContent ( );时,应用程序崩溃了,并抛给我一个异常:"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;
}发布于 2011-08-09 09:46:40
我在reflector中反映了框架模板代码。我发现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;
}https://stackoverflow.com/questions/6979974
复制相似问题