如何使用 MVVM 从 WPF 对话框中获取值

发布于 2024-11-07 22:38:12 字数 392 浏览 0 评论 0原文

从使用 MVVM 模式创建的 WPF 对话框中获取值的最佳方法是什么。我当前的代码涉及获取 ViewModel 并从中获取适当变量的额外步骤。我想避免这一步,因为它看起来有些无关紧要。

private void OpenDataSeriesWindow()
{
   var addVehicle = new AddResultsSeries();

   addVehicle.ShowDialog();

   AddResultsSeriesViewModel tempViewModel = (AddResultsSeriesViewModel)addVehicle.DataContext;
   PlotVariables.Add(tempViewModel.NewSelectedVariable);
}

What is the best way to get a value out of a WPF dialog box that was created with the MVVM pattern. My current code involves the extra step of getting the ViewModel and getting the appropriate variable out of it. I would like to avoid that step as it seems some what extraneous.

private void OpenDataSeriesWindow()
{
   var addVehicle = new AddResultsSeries();

   addVehicle.ShowDialog();

   AddResultsSeriesViewModel tempViewModel = (AddResultsSeriesViewModel)addVehicle.DataContext;
   PlotVariables.Add(tempViewModel.NewSelectedVariable);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情感失落者 2024-11-14 22:38:12

我通常这样处理:

  1. 想要显示对话框的 ViewModel 为特定对话框构造 CustomDialogViewModel。它还可以使用初始参数设置 ViewModel。

  2. View提供了显示对话框的界面。例如,如果我有一个 CustomViewModel,则 CustomWindow 将实现 ICustomView,并将其注入到 CustomViewModel 的构造函数中。 ICustomView 将提供一个方法 ShowCustomDialog(CustomDialogViewModeldialogViewModel)

  3. ViewModel 调用 View 界面上的 ShowDialog 方法。当调用返回时,它可以使用 DialogViewModel 上的属性来查看结果。

这使 ViewModel 与特定 View 实现很好地解耦,并允许您在单元测试时注入模拟 IView。这允许您编写测试来感知对话框已使用预期参数打开并相应地提供结果。

I usually go about it this way:

  1. The ViewModel that wants to show a dialog constructs the CustomDialogViewModel for the specific dialog. It can also set up the ViewModel with initial parameters.

  2. The View provides an interface for displaying the dialog. For instance, if I had a CustomViewModel, the CustomWindow would implement ICustomView, which is injected into to the constructor of CustomViewModel. ICustomView would provide a method ShowCustomDialog(CustomDialogViewModel dialogViewModel).

  3. The ViewModel calls the ShowDialog method on the View interface. When the call returns, it can use the properties on the DialogViewModel to see the result.

This keeps the ViewModel nicely decoupled from the specific View implementation and allows you to inject a mock IView when unit testing. This allows you to write tests that sense the dialog has been opened with expected parameters and supply results accordingly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文