0

我建立了一个小视图定位器。

public abstract class ViewModelLocatorBase : IViewModelLocator
{
    private readonly static bool isExecutingInDesignMode = 
                                 DesignMode.DesignModeEnabled;

    public IViewModel ViewModel
    {
       get { return isExecutingInDesignMode 
                    ? LocateDesignTimeViewModel() 
                    : LocateRuntimeViewModel(); }
    }

    protected abstract IViewModel LocateDesignTimeViewModel();

    protected abstract IViewModel LocateRuntimeViewModel();

}

用于构建更具体的视图定位器

public class UserEditorViewModelLocator : ViewModelLocatorBase
{
    protected override IViewModel LocateDesignTimeViewModel()
    {
        return new UserEditorViewModelDesignTime();
    }

    protected override IViewModel LocateRuntimeViewModel()
    {
        return new UserEditorViewModelRunTime();

    }
}

我的视图使用这些来定位正确的视图模型

public abstract class ViewBase : UserControl
{
    public ViewBase()
    {
        BindViewModelLocatorToView(viewModelLocator: GetViewModelLocator());
    }

    protected abstract IViewModelLocator GetViewModelLocator();

    protected void BindViewModelLocatorToView(IViewModelLocator viewModelLocator)
    {
        if (viewModelLocator != null)
        {
            DataContext = viewModelLocator.ViewModel;
        }
    }
}

通过在派生视图中提供正确的视图定位器(最终通过 IoC 注入)

public sealed partial class UserEditorScreen : ViewBase
{
    public UserEditorScreen()
    {
        this.InitializeComponent();
    }

    protected override IViewModelLocator GetViewModelLocator()
    {
        return new UserEditorViewModelLocator();
    }
}

现在,这一切都在运行时完美运行,但在设计时视图由于调用 BindViewModelLocatorToView 而中断。我一直在 Xaml 中直接使用这些视图定位器作为静态资源,因此它们在设计时似乎确实以这种方式工作,但是由于在视图的构造函数中填充 DataContext 的更改我错过了设计时 ViewModel。

错误

在此处输入图像描述

4

1 回答 1

1

在 C# 中,抽象类不能有公共构造函数并且违反抽象规则

请参阅此处的 MSDN http://msdn.microsoft.com/en-us/library/ms182126(v=vs.100).aspx

来自 MSDN 的规则描述:

抽象类型的构造函数只能由派生类型调用。因为公共构造函数创建类型的实例,而您不能创建抽象类型的实例,所以具有公共构造函数的抽象类型设计不正确。

因此,您可以通过这种方式在您的抽象类中使用受保护的构造函数

public abstract class ViewBase : UserControl
{
    protected ViewBase()
    {
于 2012-07-22T16:18:47.050 回答