1

在尝试了许多不同的解决方案后,我不断地回到这个问题上。我需要一个 Window.ShowDialog,通过 UnityContainer 将 ViewModelLocator 类用作工厂。

基本上我有一个视图(和 ViewModel),在视图上按下按钮需要创建一个对话框(在其构造函数中采用几个参数),它将处理一些逻辑并最终将结果返回给调用者(连同它计算的所有逻辑的结果)。

也许我仍然从 Windows 窗体的角度来看这是错误的,但我确切地知道我想要做什么,并且我想理想地使用 WPF 和 MVVM 来完成它。我正在尝试使这项工作适用于一个项目,并且最终不想回到香草 WPF 以使其工作。

4

2 回答 2

2

I break the rules to implement a dialogwindow but tried to reduce it to a minimum. I have a method OpenDialog in my BaseViewModel:

public void OpenDialog(DialogViewModel model)
{
    this.MessengerInstance.Send<DialogViewModel, MainWindow>(model);
}

And in my MainWindow:

Messenger.Default.Register<DialogViewModel>(this, model =>
        {
            // Instantiate the dialog box
            var dlg = new DialogWindow();
            // Configure the dialog box
            dlg.Owner = this;
            dlg.Content = model;
            // Open the dialog box modally 
            dlg.ShowDialog();
        });

That way i only have a loose coupling between my viewmodel and my MainView. You can do the same for closing, my BaseDialogViewModel has a method:

public void CloseDialog()
    {
        this.MessengerInstance.Send<PopUpAction, DialogWindow>(PopUpAction.Close);
    }

(PopupAction is just an enum) and my DialogWindow registers for that:

Messenger.Default.Register<PopUpAction>(this, action =>
        {
            switch (action)
            {
                case PopUpAction.Close:
                    this.Close();
                    break;
            }
        });

You could also leave the receiver away when sending, to keep the view class out of the viewmodel but either way i think it's a acceptable solution :)

于 2010-04-29T10:14:25.127 回答
0

你可以这样做。只需创建一个页面/用户控件/窗口的实例并调用instance.ShowDialog().

这是我的 T4 模板,用于生成带有关闭窗口和其他技巧的消息的视图/视图模型。

于 2010-04-28T11:21:38.027 回答