在 WPF 中,可以使用 Command 绑定来处理关闭事件,并且使用 CancelEventArgs 参数来避免窗口关闭。以下是一个示例:

首先,在 ViewModel 中定义一个 Command:

public ICommand ClosingCommand { get; set; }

然后,在构造函数中初始化 Command:

public MyViewModel()
{
    ClosingCommand = new RelayCommand<CancelEventArgs>(OnClosing);
}

private void OnClosing(CancelEventArgs e)
{
    if (MessageBox.Show('Are you sure you want to close?', 'Confirmation', MessageBoxButton.YesNo) == MessageBoxResult.No)
    {
        e.Cancel = true;
    }
}

接下来,在 View 中绑定 Command 并且传递 CancelEventArgs 参数:

<Window x:Class="MyView"
        xmlns:vm="clr-namespace:MyViewModelNamespace"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
        Title="My View">
    <Window.DataContext>
        <vm:MyViewModel />
    </Window.DataContext>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Closing">
            <ei:CallMethodAction TargetObject="{Binding}" MethodName="OnClosing" >
                <ei:CallMethodAction.Parameters>
                    <system:CancelEventArgs />
                </ei:CallMethodAction.Parameters>
            </ei:CallMethodAction>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Window>

在上述代码中,我们使用了 Microsoft.Xaml.Behaviors.Wpf 库中的 Interaction 和 CallMethodAction 类来绑定 Command 并且传递 CancelEventArgs 参数。当窗口关闭事件被触发时,Command 会被调用并且将 CancelEventArgs 参数传递给 ViewModel 的方法。在 ViewModel 中,我们可以根据需要处理 CancelEventArgs 参数并且防止窗口关闭。

WPF MVVM 绑定关闭事件并使用 CancelEventArgs 参数

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

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