我用 WPF、MVVM、Prism 和 Unity 编写应用程序。从一个窗口我启动第二个窗口:
public void ShowForm(IPrescriptionViewModel viewModel)
{
var view = new PrescriptionForm();
view.SetDataContext(viewModel);
view.ShowDialog();
}
方法 SetDataContext
public void SetDataContext(IPrescriptionViewModel viewModel)
{
if (viewModel == null) return;
DataContext = viewModel;
if (viewModel.CloseAction == null)
viewModel.CloseAction = new Action(this.Close);
}
在 BTMPrescriptionViewModel 中是一个属性
public Action CloseAction { get; set; }
和 CloseCommandExecute
public ICommand CloseCommand => new RelayCommand(CloseCommandExecute);
private void CloseCommandExecute()
{
CloseAction();
}
它工作正常,但只有一次 - 第一次。关闭二级窗口再打开后,不再用命令按钮关闭,只有窗口的关闭按钮。关闭和打开父窗口后,我可以再次使用命令按钮关闭辅助窗口,但只能关闭一次。
最佳答案
缺个好Minimal, Complete, and Verifiable code example可靠地重现问题,不可能确定问题是什么。但是,根据您在此处发布的代码,您似乎每次都在创建一个新窗口,但仅设置 CloseAction
属性(property)一次。
因为CloseAction
您分配的委托(delegate)值捕获 this
调用Close()
方法,它总是调用 Close()
在您创建的第一个窗口上,而不是您之后创建的任何窗口。
如果没有更完整的代码示例,就不清楚实现目标的最佳方式是什么。但是,如果您只是取出空检查并始终分配值,则基本问题可能会得到解决:
public void SetDataContext(IPrescriptionViewModel viewModel)
{
if (viewModel == null) return;
DataContext = viewModel;
viewModel.CloseAction = this.Close;
}
请注意,您也不需要显式调用委托(delegate)构造函数。编译器有处理委托(delegate)类型的推理规则,简单地引用方法名就足够了。
关于c# - WPF 和 MVVM : CloseAction don't work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40276989/