可以使用以下方法来实现 WPF 中 MVVM 绑定的窗口关闭事件,并阻止关闭:

  1. 在 ViewModel 中定义一个命令来处理关闭事件,例如:
public ICommand CloseCommand { get; set; }

public ViewModel()
{
    CloseCommand = new RelayCommand(Close);
}

private void Close()
{
    // 处理关闭逻辑
}
  1. 在 XAML 中绑定关闭事件到命令上,例如:
<Window x:Class="MyApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        xmlns:vm="clr-namespace:MyApp.ViewModels"
        Title="MainWindow" Height="350" Width="525">

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

    <Window.DataContext>
        <vm:ViewModel />
    </Window.DataContext>
    
    <!-- 窗口内容 -->

</Window>
  1. 在 ViewModel 中处理关闭逻辑时,可以使用 CancelEventArgs 参数来阻止关闭,例如:
private void Close(CancelEventArgs e)
{
    // 处理关闭逻辑
    
    // 阻止关闭
    e.Cancel = true;
}

这样就可以在 MVVM 模式下实现窗口关闭事件的绑定,并且可以阻止关闭。

WPF MVVM 绑定窗口关闭事件并阻止关闭

原文地址: https://www.cveoy.top/t/topic/lURF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录