我有一个抽象泛型类定义了一个通用的依赖特性,其类型是通过子类的类定义。这个属性在某种程度上不被认为是一个依赖属性,所以当绑定到这个属性时,我会在运行时收到一条错误消息。另外在编译期间,构造函数不能调用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·建议删除这些关键字。
类似的问题,这可能有助于什么:HTTP://计算器.com/questions/3629403/wpf-dependency-properties-set-in-xaml-when-base-class-is-generic –
您在代码后面继承自ListView,并且声明您从UserControl继承的XAML无法工作。 .. –
@HB对不起,示例代码是错误的。我刚刚更新了它。 – Bastian