绑定到 MVVM WPF 中的窗口关闭事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24260989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 11:56:43  来源:igfitidea点击:

Binding to Window close event in MVVM WPF?

c#wpfxamlmvvm

提问by Hardgraf

I am trying to capture the close event on my view to invoke a save method. I don't want the user to be able to close the window and dispose of un-saved changes. I have tried to use

我试图在我的视图上捕获关闭事件以调用保存方法。我不希望用户能够关闭窗口并处理未保存的更改。我试过用

Application.Current.MainWindow.Close()

But the view In question is not my MainWindow. Is there any way to bind the close window to a command from Xaml along the lines of:

但有问题的观点不是我的MainWindow. 有什么方法可以将关闭窗口绑定到 Xaml 中的命令:

public RelayCommand CloseWindow;
Constructor()
{
    CloseWindow = new RelayCommand(CloseWin);
}

public void CloseWin(object obj)
{
    Window win = obj as Window;
    win.Close();
}

& the Xaml:

&Xaml:

<Button Command="{Binding CloseWindowCommand}" CommandParameter="{Binding ElementName=WindowNameTobeClose}" Content="Cancel" />

But capturing the window close event rather than bound to a defined button in the UI?

但是捕获窗口关闭事件而不是绑定到 UI 中定义的按钮?

回答by Hardgraf

Here's my solution. Namespace in Xaml:

这是我的解决方案。Xaml 中的命名空间:

xmlns:z="http://schemas.microsoft.com/expression/2010/interactivity"

Xaml binding:

Xaml 绑定:

 <z:Interaction.Triggers>
        <z:EventTrigger EventName="Closing">
            <i:InvokeCommandAction Command="{Binding CloseWindowCommand}" />
        </z:EventTrigger>
    </z:Interaction.Triggers>

I already had a commands helper class in the project. Here's the exposed property in my viewModel:

我已经在项目中有一个命令助手类。这是我的 viewModel 中的公开属性:

   private ICommand _CloseArticleCommand;
    public ICommand CloseArticleCommand
    {
        get { return _CloseArticleCommand; }
        set
        {
            _CloseArticleCommand = value;
            OnPropertyChanged("CloseArticleCommand");
        }
    }

The property is initialized in a viewModel constructor method:

该属性在 viewModel 构造函数方法中初始化:

  private void InitialiseBtnCommands()
    {
        CloseWindowCommand = new BtnCommand(CloseWindowCommandAction);         
    }

And finally the action method which performs the save:

最后是执行保存的操作方法:

 private void CloseWindowCommandAction()
        {
            //Save your data etc.                
        }