[英]Design Time View Not Showing
我建立了一个小视图定位器。
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的调用,View中断了。 我一直在Xaml中直接使用这些视图定位器作为StaticResources,因此它们在设计时似乎确实可以使用这种方式,但是由于更改了在视图的构造函数中填充DataContext的工作,因此我错过了设计时的ViewModel。
错误
在C#中,抽象类不能具有公共构造函数,并且违反抽象规则
在此处查看MSDN http://msdn.microsoft.com/zh-cn/library/ms182126(v=vs.100).aspx
来自MSDN的规则描述:
抽象类型的构造函数只能由派生类型调用。 因为公共构造函数创建类型的实例,并且您不能创建抽象类型的实例,所以具有公共构造函数的抽象类型的设计不正确。
因此,您可以在Abstrat类中使用构造函数,以这种方式进行保护
public abstract class ViewBase : UserControl
{
protected ViewBase()
{
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.