c# - 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 中的按钮并关闭包含它。
我使用RelayCommand
andBinding
来执行命令。
有没有比使用var window = Application.Current.Windows[0];
获取当前打开的窗口的引用,然后关闭它更好的方法来关闭当前窗口?
解决方案
推荐阅读
- python - Python pydub AudioSegment MemoryError
- java - 在 Java 中创建方法(初学者)
- coq - 为什么去除假设会改变归纳策略的行为?
- python - 将 Geodataframe 写入 geopandas 中的文件时出现“不支持的驱动程序”错误
- javascript - 如何从自动完成列表中删除以前选择的项目
- verilog - 将整个寄存器数组设置为零
- python - 读取股票数据时出错:“DatetimeProperties”对象没有属性“weekday_name”,“NoneType”对象没有属性“to_csv”
- opencv - 用于 OpenCV 问题的 Video4Linux Y12 像素格式
- java - 从 xml 中获取特定值
- schema.org - 谷歌搜索似乎不再识别 schema.org/Review 或者我犯了一个错误