Caliburn Micro的窗口管理器能够经过ViewModel建立窗口,你只须要传递一个ViewModel实例给窗口管理器,窗口管理器就会自动查找对应的View,并做为一个窗口或对话框打开,在打开前还能够对view的部分依赖属性进行配置。markdown
窗口管理器在CM中很是重要,应用程序建立新窗口,弹出对话框等使用窗口管理器都是很是方便的。可是在CM中WindowManager在每一个平台(WPF、Silverlight、WindowsPhone、WinRT)上的实现都不相同。因此,想彻底了解有点困难,就连官方文档都没有详细说明。因此,为了简便起见,本文也只对WPF上的WindowManager进行介绍。app
要使用窗口管理器,就须要有一个窗口管理器的对象。咱们一般作法就是在Bootstrapper中配置IOC时,建立一个WindowManager并导入到IOC容器(能够参考学习以前Bootstrapper配置相关文章)。配置IOC的代码能够是这样的(在本文中都是以MEF为IOC容器为示例的):ide
protected override void Configure() { container = new CompositionContainer(new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>())); CompositionBatch batch = new CompositionBatch(); batch.AddExportedValue<IWindowManager>(new WindowManager()); batch.AddExportedValue(container); container.Compose(batch); }
而后咱们在须要使用WindowManager的ViewModel中提取WindowManager对象。具体作法以下:函数
[Export(typeof(ShellViewModel))] public class ShellViewModel : PropertyChangedBase { private readonly IWindowManager _windowManager; [ImportingConstructor] //必须加入这个,这是由于用MEF在建立ShellViewModel实例时,有[ImportingConstructor]标记的构造函数的参数会自动使用容器内相应的export对象 public ShellViewModel(IWindowManager windowManager) { _windowManager = windowManager; } ... }
使用WindowManager反而很简单,以下代码会建立一个新的ShellViewModel,并根据ShellViewModel找到ShellView,而后显示ShellView窗口,ShellViewModel会成为ShellView的dataContext。布局
public void NewWindow() { _windowManager.ShowWindow(new ShellViewModel(_windowManager)); }
Window Manager中打开窗口,对话框和弹出窗口,均可以,只须要调用不一样的方法便可。你能够在 Caliburn Micro 自带的 HelloWindowManager 示例中,看到WindowManager窗口管理器的更多用法。学习
在WindowManager建立窗口时,能够传递参数给新的窗口的属性。这能更好的使您根据您的须要,更细的控制您的应用程序。能够参考以下示例:atom
public void NewWindow() { var settings = new Dictionary<string, object> { { "Topmost", true }, { "Owner", GetView() } }; //Owner不是依赖属性不能绑定,但在这里设置是能够的 _windowManager.ShowDialog(new ConfigViewModel(), null, settings); }
上述示例中,我把新窗口的Topmost设置为true,Owner设置为当前ViewModel绑定的窗口(若是当前ViewModel继承了ViewAware或Screen等,就能够调用GetView方法获取View对象)。url
有些状况下,实现自定义的窗口管理器是有用的。若是你须要在全部窗口实例中设置属性都是同样的值,用它就很好。例如,属性可能包括icon图标,窗口状态,窗口大小和自定义程序样式。我发如今Windows中最常设置的属性是“SizeToContent”。默认状况下,Caliburn Micro是设置SizeToContent.WidthAndHeight。这意味着该窗口根据它的内容自动调整自身大小。虽然有时能够方便的这样作,但我发现这会致使一些问题:某些应用程序的布局和设置窗口时,默认状况下最大化会致使越界。spa
建立一个自定义的窗口管理器是很是简单的。首先添加一个继承于“WindowManager”的类,接下来,能够重写“EnsureWindow”方法,作一些相似以下:.net
protected override Window EnsureWindow(object model, object view, bool isDialog) { Window window = base.EnsureWindow(model, view, isDialog); window.SizeToContent = SizeToContent.Manual; return window; }
在这个方法中,咱们首先经过调用base.EnsureWindow()来建立窗口实例。接下来,你能够设置一下你想要的窗口中的属性,而后简单地返回窗口实例。
以后只须要用自定义窗口管理器代替默认的窗口管理器,就能够实现你想要的效果。好比你能够用以下方式添加你的自定义窗口管理器:
batch.AddExportedValue<IWindowManager>(new AppWindowManager());
这样会致使全部使用窗口管理器的地方,报告CM内部都会采用你的自定义窗口管理器。