Home > Software engineering >  C# mvvm how to handle window close events
C# mvvm how to handle window close events

Time:04-15

I am developing a wpf mvvm app with notes. Faced with the fact that I can not process the window closing event in the viewModel. I found similar questions, but the answers used Mvvm Light, which I would like to avoid. I can process it this way:

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
    }
}

But that's not what I need. I want to handle the close event in the viewModel like this:

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
    }

But if I do this, I get the error: InvalidCastException: Could not cast object type 'System.Reflection.RuntimeEventInfo' to type 'System.Reflection.MethodInfo'. Thanks in advance for your replies.

CodePudding user response:

You can bind commands to events like this:

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

Remember to add reference to System.Windows.Interactivity:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

Take a look at https://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/ from example and more details

Edit: or call CallMethodAction instead of InvokeCommandAction, again example is in the link

  • Related