Search code examples
c#wpfmvvmdata-bindingprism

How do I close a window(XAML) from the ViewModelHelper in c#?


I want to perform onCloseCommand(object sender) method form onTimeOutCommand() method, but I don't know how to pass the required parameter passed from this method?

Plese refer the following code snippet.

XAML code:

x:name = "Recorder" // window name define in the begining


//below command is used for closing this window when user clicks on close button

Command = "{Binding CloseCommand}" CommandParameter="{Binding ElementName=Recorder}"

ViewModel Code:

CloseCommand = new DelegateCommand<object>(helper.onCloseCommand);

ViewModelHelper Code:

Note: onCloseCommand() methodis working as per expectation
onCloseCommand(object sender) // This method is used for closing the window on clicking on close button of this window
{
    if(sender != null && send is window)
    {
         (sender as window).close();
    }
}

onTimeOutCommand() // this method is used for closing the window (the window which is passed in onCloseCommand() method) automaticlly after time out of the recording
{
      how to perform onCloseCommand() from this method?
}

Solution

  • how to perform onCloseCommand() from this method?

    You have multiple options, e.g. create an attached behavior that closes the window after a certain timeout and use that from xaml, effectively leaving the view model out of the equation.

    I suggest you react to the window's Loaded event in the view model and store the window and use it later when you want to close it.

    <Window x:Class="MyWindow"
            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"
            xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
            mc:Ignorable="d">
         <i:Interaction.Triggers>
             <i:EventTrigger EventName="Loaded">
                 <i:InvokeCommandAction Command="{Binding WindowLoadedCommand}" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
             </i:EventTrigger>
         </i:Interaction.Triggers>
    
         <!--- the rest of the window here --->
    </Window>
    

    But let me refer you to this answer for a more mvvm-friendly and, more importantly, testable way to close a window from the view model:

    Make the window implement an interface and store and use that (not the full Window)!

    So WindowLoadedCommand is of type DelegateCommand<IClosable> and stores the IClosable in a field. When the timeout occurs, fetch the IClosable from the field and call Close.