带有通用代码隐藏的WPF UserControl

时间:2010-09-28 09:03:05

标签: c# .net wpf generics xaml

我有这个代码:

CustomUserControl.xaml.cs

namespace MyProject
{
    public partial class CustomUserControl<T> : UserControl
    {
        ...
    }
}

和这个xaml:

CustomUserControl.xaml

<UserControl x:Class="MyProject.CustomUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Grid>

</Grid>

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

3 个答案:

答案 0 :(得分:10)

您可以创建不带XAML文件的通用“代码隐藏”文件:

public class CustomUserControl<T>: UserControl
{ }

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

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

XAML:

<application:CustomUserControl 
     x:TypeArguments="application:Presenter"
     xmlns:application="clr-namespace:YourApplicationNamespace"
...

不幸的是,在Visual Studio 2012 Update 2(参见https://stackoverflow.com/a/15110115/355438

之前,Visual Studio设计器似乎不支持此类泛型。

答案 1 :(得分:5)

到目前为止,还没有找到我的解决方案。 主要的区别是,我有一个.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, e.g.:

        // abstract protected void MouseClick(object sender, MouseButtonEventArgs e);
    }

    public class GenericUserControl<T> : GenericUserControl
    {
        // generic properties and stuff

        public GenericUserControl()
        {
            InitializeComponent();
        }
    }

    // To use the GenericUserControl<T> in XAML, you could define:
    public class GenericUserControlString : GenericUserControl<string> { }
    // and use it in XAML, e.g.:
    // <GenericUserControlString />
    // alternatively you could probably (not sure) define a markup extension to instantiate
    // it directly in XAML
}

GenericUserControl.xaml

<UserControl x:Class="TestGenericUserControl.GenericUserControl"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        mc:Ignorable="d">
    <Grid>
        <Label Content="hello" />
    </Grid>
</UserControl>

答案 2 :(得分:3)

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

请参阅以下链接:

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

Can I specify a generic type in XAML (pre .NET 4 Framework)?

可能会在Visual Studuo的未来版本中原生支持通用控件 XAML 2009。