I have a UserControl
which is binded to a ViewModel
class.
I also have a class which contains a Command
for closing a window.
In my UserControl
I have two buttons: Save and Cancel.
My Cancel button is binded to the CloseWindow Command
and when I click it, the UserControl
is indeed closing.
I bound my Save button to a function in the ViewModel
, there I wish to perform an actual save and only then close the UserControl
. I've tried several things but I can't get it to work.
Here's my code:
The CloseWindow Command:
public static readonly ICommand CloseWindow = new RelayCommand(currentCommand => ((Window)currentCommand).Close());
The code in my xaml:
<Button x:Name="Cancel" Height="25" Width="60" HorizontalAlignment="Center" VerticalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
FontFamily="Times New Roman" Foreground="DarkRed" FontWeight="Bold" Content="Cancel" Grid.Column="1" Command="{x:Static Auxiliary_Resources:CommonCommands.CloseWindow}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"/>
<Button x:Name="Ok" Height="25" Width="60" HorizontalAlignment="Center" VerticalAlignment="Center" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
FontFamily="Times New Roman" Foreground="DarkRed" FontWeight="Bold" Content="Save" Grid.Column="2" Command="{Binding CreateContactCommand}"/>
The function in the ViewModel:
private void CreateContact(object parameter)
{
if ((!String.IsNullOrEmpty(m_contactToAdd.FirstName)) &&
(!String.IsNullOrEmpty(m_contactToAdd.LastName)) &&
(!String.IsNullOrEmpty(m_contactToAdd.BankName)) &&
(m_contactToAdd.AccountNumber != null & (m_contactToAdd.AccountNumber != 0)))
{
m_contactToAdd = Contact.CreateContact(m_contactToAdd.FirstName, m_contactToAdd.LastName,m_contactToAdd.BankName, m_contactToAdd.AccountNumber);
DbHandler.AddContact(m_contactToAdd);
}
CommonCommands.CloseWindow.Execute(null);
}
This of course crashes because I'm sending null
instead of the window.
Is there a way of achieving what I'm trying to do?
Simply send the window as the
CommandParameter
, as you have already done for yourCloseCommand
.And send it to the
Execute
method.