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

本文关键字:事件 wpf 函数 按钮 绑定 | 更新日期: 2023-09-27 17:54:59

我有一个绑定到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而不是窗口。

是否有一种方法可以实现我想要做的事情?

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

只需将窗口作为CommandParameter发送,就像您已经为CloseCommand所做的那样。

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

发送给Execute方法。

CommonCommands.CloseWindow.Execute(parameter);