我经常使用的一种更简洁的方法(个人喜好的主题)是使用 IResult 模式,这样你就可以抽象 Window 实现
视图模型
public IEnumerable<IResult> CloseMe()
{
yield return new CloseResult();
}
结果代码
public class CloseResult : Result
{
public override void Execute(ActionExecutionContext context)
{
var window = Window.GetWindow(context.View);
window.Close();
base.Execute(context);
}
}
public abstract class Result : IResult
{
public virtual void Execute(ActionExecutionContext context)
{
OnCompleted(this, new ResultCompletionEventArgs());
}
protected virtual void OnCompleted(object sender, ResultCompletionEventArgs e)
{
if (Completed != null)
Completed(sender, e);
}
public event EventHandler<ResultCompletionEventArgs> Completed;
}
编辑(仅 IoC 需要):如果您想更进一步,您可以为所有屏幕创建一个基类
public abstract class ShellPresentationModel : Screen
{
public ShellPresentationModel(IResultFactory resultFactory)
{
Result = resultFactory;
}
public IResultFactory Result { get; private set; }
}
这样,您可以更轻松地使用 IoC 注入依赖项,然后您的 VIewmodel 关闭方法将如下所示
public IEnumerable<IResult> CloseMe()
{
yield return Result.Close();
}
使用依赖的 IResult 的示例可以是
public class ShowDialogResult<TModel> : Result
{
private readonly IWindowManager windowManager;
private readonly TModel model;
private Action<TModel> configure;
public ShowDialogResult(IWindowManager windowManager, TModel model)
{
this.windowManager = windowManager;
this.model = model;
}
public IResult Configure(Action<TModel> configure)
{
this.configure = configure;
return this;
}
public override void Execute(ActionExecutionContext context)
{
if(configure != null)
configure(model);
windowManager.ShowDialog(model);
base.Execute(context);
}
}
编辑刚刚注意到我忘记添加上述 IoC 示例的示例,这里有一个子 IoC 容器模式,它看起来像这样
public IEnumerable<IResult> ShowDialog()
{
yield return Result.ShowDialog<MyViewModel>();
}
如果没有子容器模式,您需要手动将父依赖注入到子容器中
yield return Result.ShowDialog<MyViewModel>().Configure(m => m.SomeData = this.SomeData);