wpf closing事件带CancelEventArgs参数进行mvvm绑定
在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参数并且防止窗口关闭。
原文地址: https://www.cveoy.top/t/topic/E0M 著作权归作者所有。请勿转载和采集!