C#:含糊不清的匹配异常:找到含糊不清的匹配
我得到一个例外: AmbiguousMatchException:找到不明确的匹配 当打开我的窗口时,XAML被解析。我有一个基本的ViewModel类。它具有DataGrid的SelectedItem属性C#:含糊不清的匹配异常:找到含糊不清的匹配,c#,wpf,xaml,oop,mvvm,C#,Wpf,Xaml,Oop,Mvvm,我得到一个例外: AmbiguousMatchException:找到不明确的匹配 当打开我的窗口时,XAML被解析。我有一个基本的ViewModel类。它具有DataGrid的SelectedItem属性 public class BaseViewModel<T> : ViewModel, INotifyPropertyChanged where T : MyClass { protected T _selectedItem; public T SelectedIt
public class BaseViewModel<T> : ViewModel, INotifyPropertyChanged where T : MyClass
{
protected T _selectedItem;
public T SelectedItem
{
get
{
return _selectedItem;
}
set
{
_selectedItem = value;
OnPropertyChanged();
}
}
}
那么,如何使用重写属性而不获取异常呢?为什么要在派生类中重新定义属性?派生类的type参数应指定属性的类型:
public class MyInheritedClass : BaseViewModel<MyClass>
{
//no need to define a new SelectedItem property...
}
…并在派生类中重写它:
public override MyClass SelectedItem
{
get
{
return _selectedItem;
}
set
{
_selectedItem = value;
OnPropertyChanged();
//Do other stuff
}
}
如果定义基类中已经存在的属性(或依赖属性的访问器),则会发生这种情况。因为这样你就变得模棱两可了。您必须覆盖(主题:虚拟)或新建(隐藏)它。否则,WPF中发生的反射将处理歧义 例如:
public partial class My : UserControl
{
// this will make the ambiguity with the existing trigges-DP legacy accessor
public int Triggers {get;set;}
// this will not make ambiguities, because it hides the original.
// however it may cause other problems
public new object Background {get;set; }
// also OK, but needs justification as well.
public override object ExistingVirtualProperty {get;set; }
...
因为我需要为继承的类做一些特殊的事情。查看新属性中的注释,然后应该在基类中使该属性为虚拟属性,并在派生类中重写它。请参阅我编辑的答案。
public override MyClass SelectedItem
{
get
{
return _selectedItem;
}
set
{
_selectedItem = value;
OnPropertyChanged();
//Do other stuff
}
}
public partial class My : UserControl
{
// this will make the ambiguity with the existing trigges-DP legacy accessor
public int Triggers {get;set;}
// this will not make ambiguities, because it hides the original.
// however it may cause other problems
public new object Background {get;set; }
// also OK, but needs justification as well.
public override object ExistingVirtualProperty {get;set; }
...