带有通用代码隐藏的WPF UserControl

我有这个代码:

CustomUserControl.xaml.cs

namespace MyProject { public partial class CustomUserControl : UserControl { ... } } 

而这个xaml:

CustomUserControl.xaml

    

它不起作用,因为x:Class =“MyProject.CustomUserControl”与代码隐藏的generics类定义不匹配。 有没有办法让这项工作?

不幸的是,XAML不支持通用代码,你可以绕过它。

请参阅以下链接:

http://forums.silverlight.net/forums/p/29051/197576.aspx

我可以在XAML(.NET 4 Framework之前版本)中指定generics类型吗?

可能是未来版本的Visual Studuo与XAML 2009本身支持通用控件。

您可以在没有XAML文件的情况下创建通用的“代码隐藏”文件:

 public class CustomUserControl: UserControl { } 

而不是从它提供特定的类作为参数:

 public partial class SpecificUserControl : CustomUserControl { public SpecificUserControl() { InitializeComponent(); } } 

XAML:

  

不幸的是,在Visual Studio 2012 Update 2之前,Visual Studio设计器似乎不支持此类generics(请参阅https://stackoverflow.com/a/15110115/355438 )

到目前为止,还没有找到我的解决方案。 主要的区别是,我有一个.xaml文件用于通用用户控件类,而不是每个实际用户控件一个.xaml文件。

GenericUserControl.xaml.cs

 using System.Windows.Controls; namespace TestGenericUserControl { public abstract partial class GenericUserControl : UserControl { // If you use event handlers in GenericUserControl.xaml, you have to define // them here as abstract and implement them in the generic class below, eg: // abstract protected void MouseClick(object sender, MouseButtonEventArgs e); } public class GenericUserControl : GenericUserControl { // generic properties and stuff public GenericUserControl() { InitializeComponent(); } } // To use the GenericUserControl in XAML, you could define: public class GenericUserControlString : GenericUserControl { } // and use it in XAML, eg: //  // alternatively you could probably (not sure) define a markup extension to instantiate // it directly in XAML } 

GenericUserControl.xaml