我有一个抽象的泛型类,它定义了一个泛型依赖属性,其类型将由子类定义。此属性不知何故未被识别为依赖属性,因此在绑定到此属性时,我在运行时收到错误消息。此外,在编译期间,构造函数不能调用InitializeComponent
. 这是为什么?
通用抽象类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" />
PS 我也不太确定这些partial
东西是否正确完成 - R# 建议删除这些关键字。