我的 View (UserControl)中有一个数据网格,其中有一个按钮,要求是在单击该按钮时显示一个窗口。我通过为窗口创建一个对象并调用它的 show 方法来实现它,是的,这是一种错误的方式,所以,我想要一种标准的方式来实现它。
我正在使用 Prism 框架,所以我使用 windowviewmodel 中的 ViewModelLocationProvider 将窗口 View 与 Window viewmodel 映射。
var table = new Window();
table.Content = new windowViewModel();
table.Show();
这是我在单击按钮时在主视图模型中实现的代码。
它实际上是在打开一个窗口,但是, View 没有被加载到窗口上。
最佳答案
使用 IDialogService
在 Prism 7 中引入
首先对话框 View 或 ViewModel 需要实现 IDialogAware
像这样的界面:
class PopupViewModel : BindableBase, IDialogAware
{
public string Title => "Popup";
public event Action<IDialogResult> RequestClose;
public bool CanCloseDialog()
{
return true;
}
public void OnDialogClosed()
{
}
public DelegateCommand OkCommand => new DelegateCommand(() =>
{
//you can also pass any parameters you want to back pass to the caller
RequestClose.Invoke(new DialogResult(ButtonResult.OK));
});
public void OnDialogOpened(IDialogParameters parameters)
{
//here you get the parameters you passed;
}
}
那么你需要像这样注册你的 View
containerRegistry.RegisterDialog<Views.Popup>();
使用您在 ViewModel 中注入(inject)
IDialogService
并称之为 this.dialogService.ShowDialog(nameof(Views.Popup), dialogParmaters, (result)=>
{
if(result.Result == ButtonResult.OK)
{
}
});
如果您希望窗口需要实现
IDialogWindow
,您也可以注册您的自定义窗口 containerRegistry.RegisterDialogWindow<MyDialogWindow>();
关于wpf - Prism MVVM - 在 WPF 中的按钮单击命令上显示 View 模型中的弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57888941/