gpt4 book ai didi

c# - 使用ViewModel类中的MVVM的WPF关闭窗口

转载 作者:行者123 更新时间:2023-12-03 10:52:23 25 4
gpt4 key购买 nike

我认为我有:

<Button Grid.Column="2" x:Name="BackBtn" Content="Powrót" Command="{Binding ClickCommand}" Width="100" Margin="10" HorizontalAlignment="Right"/>

然后,在ViewModel中:
public ICommand ClickCommand
{
get
{

return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), _canExecute));
}
}

private void MyAction()
{
MainWindow mainWindow = new MainWindow(); // I want to open new window but how to close current?
mainWindow.Show();
// how to close old window ?
}

namespace FirstWPF
{
public class CommandHandler : ICommand
{
private Action _action;
private bool _canExecute;
public CommandHandler(Action action, bool canExecute)
{
_action = action;
_canExecute = canExecute;
}

public bool CanExecute(object parameter)
{
return _canExecute;
}

public event EventHandler CanExecuteChanged;

public void Execute(object parameter)
{
_action();
}
}
}

我不知道如何处理该问题,我想关闭当前的窗口窗体ViewModel,因为我要打开一个新窗口。

最佳答案

您可以设计窗口以接收用于表示关闭请求的上下文对象

public interface ICloseable
{
event EventHandler CloseRequest;
}

public class WindowViewModel : BaseViewModel, ICloseable
{
public event EventHandler CloseRequest;
protected void RaiseCloseRequest()
{
var handler = CloseRequest;
if (handler != null) handler(this, EventArgs.Empty);
}
}


public partial class MainWindow : Window
{
public MainWindow(ICloseable context)
{
InitializeComponent();
context.CloseRequest += (s, e) => this.Close();
}
}

关于c# - 使用ViewModel类中的MVVM的WPF关闭窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42584937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com