首页 > 解决方案 > WPF - 使用 ViewModelLocator 模式时从 UserControl ViewModel 关闭窗口

问题描述

我有一个 WPF 应用程序,我在其中使用 Windows 来容纳包含所有实际控件的 UserControls,并且其 ViewModels 完成所有实际工作。换句话说,除了作为我的 UserControls 的图形容器之外,Windows 什么都不做(我相信这是一个好习惯?)。我通过使用 ViewModelLocator 模式来结合视图和视图模型,如下所示:

namespace Frontend
{
    /// <summary>
    /// Locates and "marries" views to their corresponding viewmodels,
    /// provided they follow the standard naming convention.
    /// </summary>
    public static class ViewModelLocator
    {
        public static bool GetAutoWireViewModel(DependencyObject obj)
        {
            return (bool)obj.GetValue(AutoWireViewModelProperty);
        }

        public static void SetAutoWireViewModel(DependencyObject obj, bool value)
        {
            obj.SetValue(AutoWireViewModelProperty, value);
        }

        // Using a DependencyProperty as the backing store for AutoWireViewModel.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AutoWireViewModelProperty =
            DependencyProperty.RegisterAttached("AutoWireViewModel", typeof(bool), typeof(ViewModelLocator), new PropertyMetadata(false, AutoWireViewModelChanged));

        private static void AutoWireViewModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(d)) return;
            var viewType = d.GetType();
            var viewTypeName = viewType.FullName;
            var viewModelTypeName = viewTypeName.Replace("View", "ViewModel");
            var viewModelType = Type.GetType(viewModelTypeName);
            var viewModel = Activator.CreateInstance(viewModelType);
            ((FrameworkElement)d).DataContext = viewModel;
        }
    }
}

使用这种模式可以使视图和视图模型自行排序,这很好,但是我没有对视图模型中的视图的任何引用,所以现在我希望能够单击 UserControl 中的按钮并关闭包含它。

我使用RelayCommandandBinding来执行命令。

有没有比使用var window = Application.Current.Windows[0];获取当前打开的窗口的引用,然后关闭它更好的方法来关闭当前窗口?

标签: c#wpf

解决方案


推荐阅读