2012-09-01 45 views
2

我有一个抽象泛型类定义了一个通用的依赖特性,其类型是通过子类的类定义。这个属性在某种程度上不被认为是一个依赖属性,所以当绑定到这个属性时,我会在运行时收到一条错误消息。另外在编译期间,构造函数不能调用InitializeComponent。这是为什么?泛型UserControls和泛型依赖属性可能吗?

通用抽象类MyClass

abstract public class MyClass<T,U> : UserControl { 
    protected MyClass() { 
     InitializeComponent(); // Here is one error: Cannot be found 
    } 

    abstract protected U ListSource; 

    private static void DPChanged 
    (DependencyObject d, DependencyPropertyChangedEventArgs e) { 
     var myClassObj = (MyClass) d; 
     myClassObj.DataContext = myClassObj.ListSource; 
    } 

    // Causes a binding error at runtime => DP (of the concrete subclass) 
    // is not recognized as a dependency property 
    public static readonly DependencyProperty DPProperty = 
     DependencyProperty.Register(
     "DP", 
     typeof(T), 
     typeof(MyClass), 
     new PropertyMetadata(null, DPChanged)); 

    public T DP { 
     get { return (T) GetValue(DPProperty); } 
     set { SetValue(DPProperty, value); } 
    } 
} 

相应XAML:

<UserControl x:Class="Path.of.Namespace.MyClass" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <ListView> 
     <!-- Some stuff for the list view - used for all subclasses --> 
    </ListView> 
</UserControl> 

具体子类MySubClass

public partial class MySubClass : MyClass<ClassWithAList, List<int>> { 
    public MySubClass() { 
     InitializeComponent(); // Another error: Cannot be found 
    } 

    protected List<int> ListSource { 
     get { return new List<int>(); } // Just a dummy value 

    } 
} 

相应XAML:

<local:MySubClass xmlns:local="Path.of.Namespace.MySubClass" /> 

附:我也不太清楚,如果partial东西做得正确 - R·建议删除这些关键字。

+0

类似的问题,这可能有助于什么:HTTP://计算器.com/questions/3629403/wpf-dependency-properties-set-in-xaml-when-base-class-is-generic –

+1

您在代码后面继承自ListView,并且声明您从UserControl继承的XAML无法工作。 .. –

+0

@HB对不起,示例代码是错误的。我刚刚更新了它。 – Bastian

回答

1

我认为有几件事情你的代码错误,但首先,让我在这方面解释partial

partial用于在单独的文件来声明一个类。当视觉工作室创建一个MySubClass.g.cspartial class MySubClass(btw。这是InitializeComponent被声明的地方)从你的MySubClass.xaml你会有这个类声明两次,因此为了得到这个编译你将需要partial关键字。

现在到休息:XAML和泛型不能很好地结合在一起,这意味着:根本不是。你的'相应的XAML'声明MyClass。但没有泛型参数的MyClass不存在。你可以在这一点上的变化x:Class="Path.of.Namespace.MyClass"x:Class="Path.of.Namespace.MySubClass",应该工作。

但现在接下来的事情是:你如何访问xaml中的依赖属性?它是在一个泛型类型的静态成员,所以你必须在这样的代码指定:MyClass<ClassWithAList, List<int>>.DPProperty。这个问题又是:你不能这样做,在XAML

解决你的问题可能是一个好主意,告诉我们你想在这里完成

+0

谢谢你的好解释。实际上,我试图达到的目标也可能不使用泛型。我只是想避免在每个子类中重新定义依赖属性 - 现在我只是坚持更加详细的解决方案(通过不使用泛型)。 – Bastian

0

我想问题可能是你正在写的typeof(MyClass的),而应该是typeof(MyClass<T,U>)