So, I have this command call CloseCommand in my Commands folder. I also have a WindowViewModel class in my ViewModels folder. Here's the content inside the WindowViewModel:
using Test.Commands;
namespace Test.ViewModels
{
public class WindowViewModel
{
#region Window
public MainWindow mainWindow { get; set; }
public CloseCommand CloseCommand{ get; set; } = new CloseCommand();
#endregion
public WindowViewModel(MainWindow mainWindow)
{
this.mainWindow = mainWindow;
Test = "Hello";
CloseCommand.mainWindow = this.mainWindow;
}
public WindowViewModel() { }
}
}
Here's the content inside the CloseCommand class:
using System;
using System.Windows;
using System.Windows.Input;
namespace Test.Commands
{
public class CloseCommand: ICommand
{
public event EventHandler CanExecuteChanged;
public MainWindow mainWindow { get; set; }
public CloseCommand(MainWindow mainWindow)
{
this.mainWindow = mainWindow;
}
public CloseCommand() { }
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
MessageBox.Show("Press OK to close");
mainWindow.Close();
}
}
}
Here's the content inside the MainWindow.xaml:
<Window.Resources>
<!-- I have already defined "commands" when defining Window-->
<commands:CloseCommand x:Key="CloseCommand"/>
</Window.Resources>
<Grid>
<Button Content="{Binding Test}" Background="Blue" Foreground="White" FontSize="50" Command="{StaticResource CloseCommand}"/>
</Grid>
Now, when I run the program and press my button, it display the MessageBox I had defined in the CloseCommand.Execute
method, but after I press the OK button in the MessageBox
, it gives me an error:
mainWindow property is null.
I expect this problem happens because the CloseCommand
is converted to an ICommand when I defined it in my MainWindow.xaml and in the Command property of the Button
. So how do I fix this problem? Is my expectations right? Please correct me.