C# 在Caliburn.Micro中将派生的视图模型映射到基类视图
我有一个基本视图模型和关联视图。我还有多个从基础视图模型派生的视图模型,但我想使用基础视图进行显示 基本视图模型和视图:C# 在Caliburn.Micro中将派生的视图模型映射到基类视图,c#,wpf,mvvm,caliburn.micro,C#,Wpf,Mvvm,Caliburn.micro,我有一个基本视图模型和关联视图。我还有多个从基础视图模型派生的视图模型,但我想使用基础视图进行显示 基本视图模型和视图: vm:MyCompany.MyApp.Modules.Wizard.ViewModels.WizardViewModel vw:MyCompany.MyApp.Modules.Wizard.Views.WizardView 源于向导视图模型: vm:MyCompany.MyApp.Modules.NewSpec.ViewModels.NewSpecViewModel:W
- vm:
MyCompany.MyApp.Modules.Wizard.ViewModels.WizardViewModel
- vw:
MyCompany.MyApp.Modules.Wizard.Views.WizardView
- vm:
MyCompany.MyApp.Modules.NewSpec.ViewModels.NewSpecViewModel:WizardViewModel
- vw:(映射到
)MyCompany.MyApp.Modules.Wizard.Views.WizardView
- vm:
MyCompany.MyApp.Modules.NewSpec.ViewModels.NewMaterialViewModel:WizardViewModel
- vw:(映射到
)MyCompany.MyApp.Modules.Wizard.Views.WizardView
public class NewSpecViewModel : WizardViewModel
{
// ...
static NewSpecViewModel()
{
// Escape the '.' for the regular expression
string nsSource = typeof(NewSpecViewModel).FullName.Replace(".", @"\.");
string nsTarget = typeof(WizardViewModel).FullName;
nsTarget = nsTarget.Replace("WizardViewModel", "Wizard");
// nsSource = "MyCompany\\.MyApp\\.Modules\\.NewSpec\\.ViewModels\\.NewSpecViewModel"
// nsTarget = "MyCompany.MyApp.Modules.Wizard.ViewModels.Wizard"
ViewLocator.AddTypeMapping(nsSource, null, nsTarget);
}
// ...
}
另外,我知道有现有的向导框架(,等等),但我不想再添加第三方程序集,而且扩展WPF工具包向导无法正常工作
另外,我还想在其他地方使用这种风格的基本视图模型/视图映射。这里有一个[链接]()指向正确的方法
编辑:由于codeplex正在关闭,以下是讨论中的代码:
var defaultLocator = ViewLocator.LocateTypeForModelType;
ViewLocator.LocateTypeForModelType = (modelType, displayLocation, context) =>
{
var viewType = defaultLocator(modelType, displayLocation, context);
while (viewType == null && modelType != typeof(object))
{
modelType = modelType.BaseType;
viewType = defaultLocator(modelType, displayLocation, context);
}
return viewType;
};
我知道已经很晚了。。。
但是有一个选项可以将ViewModel
直接绑定到视图,这可能会帮助其他人
我还将把这个绑定附加到基类构造函数中。以下是我的作品:
public abstract class WizardViewModel {
protected WizardViewModel() {
// this --> points the child class
ViewModelBinder.Bind(this, new WizardView(), null);
}
}
这样,每个子类现在都使用向导视图
(在子类中没有任何附加编程)
我认为这在某些情况下有效,但要小心。在这种情况下,必须在UI线程上构造ViewModel,因为视图无法初始化。
public class NewSpecViewModel : WizardViewModel {}