将按钮绑定到函数和关闭事件 wpf

Binding a button to both a function and close event wpf

我有一个 UserControl 绑定到 ViewModel class.

我还有一个 class,其中包含一个 Command 用于关闭 window。

在我的 UserControl 中有两个按钮:保存取消.

我的取消按钮绑定到CloseWindow Command,当我点击它时,UserControl确实关闭了。

我将 保存 按钮绑定到 ViewModel 中的一个函数,在那里我希望执行实际保存,然后才关闭 UserControl。我已经尝试了几件事,但我无法让它工作。

这是我的代码:

关闭窗口命令:

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 而不是 window。

有没有办法实现我想要做的事情?

只需将 window 作为 CommandParameter 发送,正如您已经为您的 CloseCommand 所做的那样。

CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"

并将其发送到 Execute 方法。

CommonCommands.CloseWindow.Execute(parameter);