c# - WPF UserControl MVVM如何关闭对话框

标签 c# wpf mvvm

我是MVVM的新手,并且遇到了如何打开对话框并随后在其自己的ViewModel C#文件中关闭对话框的问题。搜索可能的解决方案,但没有找到合适的解决方案。
我的解决方案如下所示,但是我不确定这是否有缺点。
定义了一个UserControl并使用以下命令打开它:

void ChangeDataPathExecute()
{
    Window window = new Window
    {
        Content = new ChangeDataRootPathUserControl(),
    };

    window.ShowDialog(); 
}

在UserControl文件的ViewModel中实现:
private void DetermineMyWindow()
{
    foreach (Window window in App.Current.Windows)
    {
        ChangeDataRootPathUserControl uc = window.Content as ChangeDataRootPathUserControl;
        if (uc == null)
            continue;

        myWindow = window;
    }

最后在Close方法中:
void OkChangeDataRootPathExecute()
{
    DetermineMyWindow();

    myWindow.Close();
}

你怎么看待这件事?哈克还是好的解决方案?
感谢您的反馈

最佳答案

MVVM场景中的ViewModel不必了解有关View的任何信息。在您的示例中,它似乎必须对 View 了解很多。

许多人使用许多不同的模式从ViewModel打开/关闭窗口。我更喜欢事件/回调:

class ViewModel {
    public event EventHandler ChangeDataRootPath;
}

class View : Window {
    public View() {
        InitializeComponent();

        var vm = new ViewModel();
        vm.ChangeDataRootPath += (s, e) => {
            Window window = new Window {
                Content = new ChangeDataRootPathUserControl {
                    DataContext = vm
                }
            };
            window.ShowDialog(); 
        };
        DataContext = vm;
    }
}

关于c# - WPF UserControl MVVM如何关闭对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10837170/

相关文章:

c# - WPF TabControl with Materials Design(没有 Dragablz)

C#/WPF - 全局更改游标

c# - CollectionViewSource 违反 MVVM

wpf - 关闭命令 WPF

.net - 处理 ViewModel 内的 WPF 对象

c# - 为 UserControl 填充模型的正确方法是什么?

c# - 如何使用 linq 选择锯齿状数组的列

c# - ASP.NET Core 无法使用 RazorViewEngine 按路径找到 cshtml 文件

c# - WPF 在用户控件上剪切、复制、粘贴功能

c# - 将子对象转换为父类型以进行序列化