如何从在 wpf mvvm 模式中作为窗口打开的视图模型中关闭用户控件?



我正在尝试从视图模型按钮命令中作为窗口/对话框打开的视图模型中关闭用户控件。

将用户控件打开为窗口/对话框: 主窗口>>按钮 通过主窗口视图>>命令模型>>将用户控件显示为窗口/对话框

关闭在上述步骤中打开的用户控件:????

我也想知道我是否违反了 mvvm 模式,所以如果有人可以给我一些合适的例子,因为我对 wpf MVVM 模式相当陌生。

视图中的主窗口按钮命令模型:

private void ExecuteOtherMethod(object parameter)
{

registerWindow win = (registerWindow)Application.Current.MainWindow;
//win.pp.IsOpen = true;
win.bankRectangle.Visibility = Visibility.Visible;
Window window = new Window
{
WindowStyle = WindowStyle.None,
SizeToContent = SizeToContent.WidthAndHeight,
ResizeMode = ResizeMode.NoResize,
Content = new otherOptionsView()
};
window.Owner = win;
window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
window.ShowDialog();

}

用户控件视图模型关闭用户控件:

private void ExecuteMethod(object parameter)
{
//otherOptionsView newview = new otherOptionsView();
//Window parentWindow = (Window)newview.Parent;
//parentWindow.Close();
var displayViews = App.Current.Windows.OfType<otherOptionsView>();
if (displayViews.Any())
displayViews.First().Close();
registerWindow win = (registerWindow)Application.Current.MainWindow;
win.bankRectangle.Visibility = Visibility.Collapsed;

}

一种方法是根本没有窗口(如果它不是主窗口(,就像这里接受的答案一样 使用 MVVM 处理 WPF 中的对话框。在窗口中有一个自由浮动用户控件,并将其可见性绑定到视图模型中的布尔值。

您还可以引发事件并在视图中处理它,就像在 WPF (MVVM( 中一样:从视图模型关闭视图?。

另一种方法是使用 ViewModel 信使或调解器。这需要在视图中使用代码隐藏,并且通常不用于视图模型和视图之间的通信。将视图注册到中介器类,并侦听视图模型通过调解器发送的特定"关闭"请求。如使用 MVVM Light 的信使在视图模型之间传递值

另外,如果您实际上正在尝试关闭主窗口,为什么不使用Application.Current.Shutdown()

对于窗口管理,您始终可以使用 nuget 包"MvvmDialogs",它是专门为帮助您处理窗口父子关系而设计的,并且具有相当大的示例应用程序集合。

最新更新