C#:AmbigeousMatchException:发现不明确的匹配

标签 c# wpf xaml oop mvvm

我得到了异常:

AmbiguousMatchException: ambiguous match found

当打开我的窗口并且 XAML 被解析时。我有一个基本 ViewModel 类。它有一个 DataGrid 的 SelectedItem 属性

public class BaseViewModel<T> : ViewModel, INotifyPropertyChanged where T : MyClass
{
    protected T _selectedItem;
    public T SelectedItem
    {
        get
        {
            return _selectedItem;
        }
        set
        {
            _selectedItem = value;
            OnPropertyChanged();
        }
    }
}

在我继承的 ViewModel 中,我重写了产生异常的属性

public new MyInheritedClass SelectedItem
{
    get
    {
        return _selectedItem;
    }
    set
    {
        _selectedItem = value;
        OnPropertyChanged();
        //Do other stuff
    }
}

那么如何使用重写的属性而不出现异常?

最佳答案

为什么要在派生类中重新定义属性?派生类的类型参数应指定属性的类型:

public class MyInheritedClass : BaseViewModel<MyClass>
{
    //no need to define a new SelectedItem property...
}

在上面的示例代码中,MyInheritedClass 已经具有类型为 MyClassSelectedItem 属性。它已经在基类中定义了。您无需创建新的。

如果该属性需要在派生类中执行某些特殊操作,则应在基类中将该属性定义为virtual:

public virtual T SelectedItem
{
    get
    {
        return _selectedItem;
    }
    set
    {
        _selectedItem = value;
        OnPropertyChanged();
    }
}

...并在派生类中重写它:

public override MyClass SelectedItem
{
    get
    {
        return _selectedItem;
    }
    set
    {
        _selectedItem = value;
        OnPropertyChanged();
        //Do other stuff
    }
}

关于C#:AmbigeousMatchException:发现不明确的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42188340/

相关文章:

wpf - 如何绑定(bind)到静态值?

c# - DbContext SaveChanges() - 检测更新的实体

c# - 允许使用 HttpClient 的不受信任的 SSL 证书

wpf - 想要一个可视化XAML层次结构的工具,尝试过XAMLPadX有问题

WPF 组框控件模板 : How to apply a Style only to elements in the Header?

c# - GroupStyle 和 Expander.IsExpanded 绑定(bind)的问题

c# - 让相机在人像模式下正常工作

c# - 将文本文件转换为 Excel

c# - ASP.NET MVC 助手,独立于 MVC 版本

c# - 水平方向的 ItemsControl