[英]WPF Close window with MVVM from ViewModel class
我認為我有:
<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();
}
}
在這些論壇上,已經多次回答了這個問題。
我認為,最干凈的解決方案是附加屬性,如對此問題的最高評價答案所述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.