【问题标题】:Best way to close Window with MEFedMVVM使用 MEFedMVVM 关闭窗口的最佳方法
【发布时间】:2011-12-10 21:14:57
【问题描述】:

在我的应用程序中,我有一个通过 MEFedMVVM 导入 ViewModel 的 MainWindow:

xmlns:mefed="clr-namespace:MEFedMVVM.ViewModelLocator;assembly=MEFedMVVM.WPF"
mefed:ViewModelLocator.ViewModel="MainViewModel"

现在我也有我的 ViewModel 来实现 ViewModel:

[ExportViewModel("MainViewModel")]
public class MainViewModel: ViewModelBase

在我的 ViewModel 中,我有一个用于关闭窗口的 ICommand 属性。关闭事件可以来自任何地方。在 Cinch Framework 2.0 的帮助下,我实现了一个带有 Execute 方法的 Simplecommand。

问题

如何通过执行方法关闭窗口?通过依赖注入,我没有构造函数,我无法注册事件或将视图作为参数提供给视图模型。

编辑

但是,我认为不太好的可能性:

在方法中调用这个

Application.Current.MainWindow.Close()

【问题讨论】:

    标签: wpf c#-4.0 mvvm mef mefedmvvm


    【解决方案1】:

    您可以通过编写ICommand 来实现此目的,该Window 实例作为参数传入。

    这里有一个很好的例子:How can I assign the 'Close on Escape-key press' behavior to all WPF windows within a project?

    在那篇文章中,ICommand 最终绑定到 KeyBinding(以便可以使用 Escape 键关闭窗口),但是您可以将命令绑定到任何按钮或从内部的任何位置调用它风景。重要的部分是在您的命令参数绑定上使用RelativeSource 来引用您要关闭的Window

    编辑以响应 cmets

    该命令是一个单例,但没有要求它是一个单例 - 它只是一个单例,因为它是无状态的,并且它使绑定更容易。它通过绑定获取对Window 的引用,因此对于UserControl,您可以使用:

    <Button Command="{x:Static mynamespace:CloseWindowCommand.Instance}"
        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" Content="Close My Parent Window" />
    

    能够从视图模型代码中调用它稍微复杂一些,需要不同的方法;一个很好的例子可以在这里找到:http://gallery.expression.microsoft.com/WindowCloseBehavior

    【讨论】:

    • 在这个示例中,de CloseCommand 是 Singleton 对吗?我可以从任何地方调用执行?但是单例类是如何获取 View 的实例的呢?我不需要键绑定。该命令来自计时器或子视图(用户控件)。
    猜你喜欢
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    相关资源
    最近更新 更多