我有一个绑定到ViewModel
类的UserControl
。
我也有一个类,其中包含一个Command
关闭窗口。
在我的UserControl
我有两个按钮:保存和取消。
我的取消按钮绑定到CloseWindow Command
,当我点击它时,UserControl
确实关闭。
我将Save按钮绑定到ViewModel
中的一个功能,在那里我希望执行实际保存,然后关闭UserControl
。我试了好几种方法,但都不行。
下面是我的代码:
CloseWindow命令:
public static readonly ICommand CloseWindow = new RelayCommand(currentCommand => ((Window)currentCommand).Close());
我的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}"/>
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);
}
这当然会崩溃,因为我发送的是null
而不是窗口。
是否有一种方法可以实现我想要做的事情?
只需将窗口作为CommandParameter
发送,就像您已经为CloseCommand
所做的那样。
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
发送给Execute
方法。
CommonCommands.CloseWindow.Execute(parameter);