gpt4 book ai didi

wpf - 我应该如何在 MVVM 中处理这种常见的 UI 场景?

转载 作者:行者123 更新时间:2023-12-03 10:21:12 25 4
gpt4 key购买 nike

场景:

  • 父窗口加载、填充数据(网格、标签等)
  • 用户单击按钮,在父窗口的 ViewModel 中触发绑定(bind)命令,启动编辑对话框
  • 用户在编辑对话框中进行更改并单击“接受”,将一些信息保存到数据库
  • 父窗口的 ViewModel 识别出发生了一些事情(注意到 dialog.DialogResult == true ),并且它应该刷新它的数据和任何相关的绑定(bind)

  • 还要考虑到第 3 步可能由于某种原因而失败(复杂的业务逻辑规则可能会失败,用户需要调整一些东西,数据库更新可能会引发异常、僵尸入侵等),因此编辑对话框可能必须保持打开状态.

    ViewModel 不应该(据我了解)对其关联的 View 了解太多/任何信息,因此 ViewModel 很难与 View 进行通信:

    "Hey, the Save operation completed successfully! Go ahead and close now!"



    或者:

    "Whoa! There was a problem that needs to be taken care of before you can close... wait a tick."



    问题:

    这样的事情是如何优雅地完成的,只需要很少 xaml.cs尽可能编码(最好没有)?

    最佳答案

    通常在做这样的事情时,我会将对话窗口的打开交给一个服务,以后可以为了测试目的进行模拟。就像是:

    public interface IDialogProvider
    {
    bool OpenDialog(IViewModel viewModel)
    }

    然后可以将传入的viewmodel绑定(bind)为模态窗口的DataContext,并通过数据模板使用正确的 View 。

    当命令被触发打开 subview 时,父 View 模型可以使用该服务。 child 可以进行所需的所有处理,并且可以从 child 那里获得真实结果所需的任何信息:
    public void ExecuteEdit()
    {
    ChildViewModel childViewModel = GetViewModelForSelectedItem();
    if (_dialogProvider.OpenDialog(childViewModel)
    {
    //child view model saved, trigger rebinding etc...
    }
    }

    如果您有这些对话框使用的 View 模型的特定基类,要处理错误场景,您可以在后面添加一些代码来处理窗口的关闭。我会在 View 模型中使用与 View 无关的事件,并在触发此事件时关闭窗口。在 View 中:
    public DialogWindowView()
    {
    InitializeComponent();
    DataContexctChanged += HandleDataContextChanged;
    }

    private void HandleDataContextChanged(object sender, EventArgs e)
    {
    IDialogViewModel viewModel = DataContext as IDialogViewModel;

    if (viewModel != null)
    {
    viewModel.ActionSuccessful += HandleActionSuccessful
    }
    }

    private void HandleActionSuccessful(object sender, EventArgs e)
    {
    DialogResult = DialogResult.OK;
    Close();
    }

    我对这个代码作为 View 完全没有问题,因为 View 模型不负责处理事物的外观,包括打开或关闭窗口。如果您完全反对背后代码的想法,或者您不想将 View 耦合到 View 模型类型,则可以将责任转移到 DialogProvider 上:
    public class DialogProvider : IDialogProvider
    {
    public bool OpenDialog(IDialogViewModel viewModel)
    {
    Window dialog = new DialogWindow();
    dialog.DataContext = viewModel;
    bool success = false;
    viewModel.ActionSuccessful = (o, e) =>
    {
    dialog.Close();
    success = true;
    }

    dialog.ShowDialog();

    return success;
    }
    }

    关于wpf - 我应该如何在 MVVM 中处理这种常见的 UI 场景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3532069/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com