【问题标题】:How to derive a new class from DataTemplate and then use it in place of DataTemplate?如何从 DataTemplate 派生一个新类,然后用它代替 DataTemplate?
【发布时间】:2009-06-12 09:51:58
【问题描述】:

如何从 DataTemplate 派生一个新类,然后用它代替 DataTemplate?

例如,在 C# 中:

public class DerivedDataTemplate : DataTemplate
{
}

然后在 XAML 中:

<local: DerivedDataTemplate DataType="{x:Type local:SomeType}">
    <Grid>
        ... UI here ...
    </Grid>
</local:DerivedDataTemplate>

当我尝试使用我的派生数据模板类时,会生成以下异常:

System.Windows.Markup.XamlParseException 未处理 Message="'Grid' 对象无法添加到 'DerivedDataTemplate'。'System.Windows.Controls.Grid' 类型的对象无法转换为 'System.Windows.FrameworkElementFactory' 类型。

有谁知道如何解决这个异常并成功使用派生自 DataTemplate 的类?

【问题讨论】:

  • 出于好奇,您为什么要从 DataTemplate 继承?
  • 我基本上希望能够拥有一种特殊的数据模板,我可以将额外的数据附加到并使用内置规则进行资源搜索和模板实例化。我最终采用了不同的方式 - 但从 DataTemplate 继承会更简单。

标签: c# wpf xaml datatemplate


【解决方案1】:

它对我有用(尽管我没有创建本地类型)。我复制了您的代码,并且必须删除 XAML 声明中 local: 和 DerivedDataTemplate 之间的空格。在 Blend 3 中它甚至不会为我运行,我不确定 Blend 2。

【讨论】:

  • 这个空间只是一个拼写错误,我的真实代码没有那个错误。所以当你说它对你有用时,你到底是什么意思?在下一句中,您似乎说它对您不起作用!?我正在使用 Visual Studio 2008 Express。
  • 抱歉,我不清楚:您的代码在没有空格的情况下对我有用。 它甚至不会在 Blend 3 中运行的空间。
猜你喜欢
  • 2011-01-05
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多