我正在开发一个wpf mvvm应用程序与笔记。面对这样一个事实,我无法在viewModel中处理窗口关闭事件。我发现了类似的问题,但答案使用Mvvm,这是我想要避免的。我可以这样处理:
FindNoteWindow.xaml
<Window x:Class="NotesARK6.View.FindNoteWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
DataContext="{Binding Path=FindNoteWindowViewModel, Source={StaticResource ViewModelLocator}}"
mc:Ignorable="d"
Closing="Window_Closing"
Title="FindNoteWindow" Height="250" Width="400">
FindNoteWindow.xaml.cs
public partial class FindNoteWindow : Window
{
public FindNoteWindow()
{
InitializeComponent();
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// code
}
}
但这不是我需要的。我想像这样处理viewModel中的关闭事件:
FindNoteWindow.xaml
<Window x:Class="NotesARK6.View.FindNoteWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
DataContext="{Binding Path=FindNoteWindowViewModel, Source={StaticResource ViewModelLocator}}"
mc:Ignorable="d"
Closing="{Binding Window_Closing}"
Title="FindNoteWindow" Height="250" Width="400">
FindNoteWindowViewModel.cs
public void Window_Closing(object sender, CancelEventArgs e)
{
//code
}
但是如果我这样做,就会得到错误: InvalidCastException:未能将对象类型'System.Reflection.RuntimeEventInfo‘转换为'System.Reflection.MethodInfo’。谢谢您的答复。
发布于 2022-04-15 08:09:32
可以将命令绑定到以下事件:
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing" >
<i:InvokeCommandAction Command="{Binding WindowClosingCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
请记住添加对System.Windows.Interactivity的引用:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
从示例和更多细节中查看https://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/
编辑:或者调用CallMethodAction
而不是InvokeCommandAction
,同样的例子在链接中。
https://stackoverflow.com/questions/71873796
复制相似问题