c# - 具有泛型的 WPF 自定义控件 - 可能吗?

标签 c# wpf generics xaml controls

我想使用泛型创建自定义 WPF 控件:

public class MyGenericTypeControl<T> : ItemsControl 
{   
   // ...
}

这可能吗?在我最初的实验中,一旦我尝试在某处添加此控件,我就会遇到设计时/编译时 XAML 错误。这并不奇怪,因为构建我的自定义控件需要 XAML 不提供的额外信息。

有什么想法吗?

最佳答案

使用 x:TypeArguments 的支持有限

For XAML 2006 usage, and XAML that is used for WPF applications, the following restrictions exist for x:TypeArguments and generic type usages from XAML in general:

  • Only the root element of a XAML file can support a generic XAML usage that references a generic type.
  • The root element must map to a generic type with at least one type argument. An example is PageFunction<T>. The page functions are the primary scenario for XAML generic usage support in WPF.
  • The root element XAML object element for the generic must also declare a partial class using x:Class. This is true even if defining a WPF build action.
  • x:TypeArguments cannot reference nested generic constraints.

关于c# - 具有泛型的 WPF 自定义控件 - 可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7027392/

相关文章:

c# - EF Core 保存所需属性的空值

c# - app.xaml 资源字符串中的 XamlParseException

java - 泛型类型参数隐藏类型

java - 在返回类型中使用通配符与定义的泛型类型有何不同?

java - 带有泛型参数的主方法;为什么它起作用?

c# - 在 C# 中模拟系统环境变量

c# - Debug 和 Release 模式之间的异常堆栈跟踪差异

c# - 后台多线程(UI 无响应)

c# - WPF 形状裁剪

wpf - WPF 超链接中的文本换行