跟进接受的答案,我想向您展示如何实现的WinForms引导程序的视图模型优先的方法,在某种程度上(好的!):
- 你赢了不必创建一个WPF窗口,并且您不必直接绑定到View中的ViewModel。
为此,我们需要建立我们自己的窗口管理器的版本,确保我们不呼吁窗口Show
方法(如果适用于您的情况),并允许发生结合。
下面是完整的代码:
public class WinformsCaliburnBootstrapper<TViewModel> : BootstrapperBase where TViewModel : class
{
private UserControl rootView;
public WinformsCaliburnBootstrapper(ElementHost host)
: base(false)
{
this.rootView = new UserControl();
rootView.Loaded += rootView_Loaded;
host.Child = this.rootView;
Start();
}
void rootView_Loaded(object sender, RoutedEventArgs e)
{
DisplayRootViewFor<TViewModel>();
}
protected override object GetInstance(Type service, string key)
{
if (service == typeof(IWindowManager))
{
service = typeof(UserControlWindowManager<TViewModel>);
return new UserControlWindowManager<TViewModel>(rootView);
}
return Activator.CreateInstance(service);
}
private class UserControlWindowManager<TViewModel> : WindowManager where TViewModel : class
{
UserControl rootView;
public UserControlWindowManager(UserControl rootView)
{
this.rootView = rootView;
}
protected override Window CreateWindow(object rootModel, bool isDialog, object context, IDictionary<string, object> settings)
{
if (isDialog) //allow normal behavior for dialog windows.
return base.CreateWindow(rootModel, isDialog, context, settings);
rootView.Content = ViewLocator.LocateForModel(rootModel, null, context);
rootView.SetValue(View.IsGeneratedProperty, true);
ViewModelBinder.Bind(rootModel, rootView, context);
return null;
}
public override void ShowWindow(object rootModel, object context = null, IDictionary<string, object> settings = null)
{
CreateWindow(rootModel, false, context, settings); //.Show(); omitted on purpose
}
}
}
我希望这可以帮助别人有同样的需求。它确实救了我。
我认为,在这种情况下,C.M.会比解决更麻烦。厘米。旨在帮助纯WPF应用程序通过其广泛/自动化的MVVM框架更快地“启动并运行”。你的应用程序已经过去了从框架构建阶段,在这个阶段引入新应用程序将是非常具有挑战性的。 最可能帮助你的是应用坚实的MVVM(艰难的方式),转换到WPF。由于该项目在WinForms中,因此它有一个非零机会,因为它是用一个体面的MVC implimentation构建的,所以向MVVM的这种转换可能不那么痛苦。祝你好运! – EtherDragon 2012-02-01 00:23:45