如何使用 MVVM 从 WPF 对话框中获取值
从使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我通常这样处理:
想要显示对话框的 ViewModel 为特定对话框构造 CustomDialogViewModel。它还可以使用初始参数设置 ViewModel。
View提供了显示对话框的界面。例如,如果我有一个 CustomViewModel,则 CustomWindow 将实现 ICustomView,并将其注入到 CustomViewModel 的构造函数中。 ICustomView 将提供一个方法
ShowCustomDialog(CustomDialogViewModeldialogViewModel)
。ViewModel 调用 View 界面上的 ShowDialog 方法。当调用返回时,它可以使用 DialogViewModel 上的属性来查看结果。
这使 ViewModel 与特定 View 实现很好地解耦,并允许您在单元测试时注入模拟 IView。这允许您编写测试来感知对话框已使用预期参数打开并相应地提供结果。
I usually go about it this way:
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.
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)
.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.