【问题标题】:Design Time View Not Showing设计时视图未显示
【发布时间】:2012-07-22 15:27:51
【问题描述】:

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

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 中直接使用这些视图定位器作为 StaticResources,因此它们在设计时似乎确实以这种方式工作,但由于更改为在视图的构造函数中填充 DataContext,我错过了设计时 ViewModel。

错误

【问题讨论】:

    标签: c# mvvm microsoft-metro winrt-xaml


    【解决方案1】:

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

    在此处查看 MSDN http://msdn.microsoft.com/en-us/library/ms182126(v=vs.100).aspx

    来自 MSDN 的规则描述:

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

    所以你可以在你的抽象类中使用构造函数作为受保护的方式

    public abstract class ViewBase : UserControl
    {
        protected ViewBase()
        {
    

    【讨论】:

    • 这解决了问题,但绑定不起作用。我会问另一个问题,因为它们似乎不相关。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多