【问题标题】:Binding a button to both a function and close event wpf将按钮绑定到函数和关闭事件 wpf
【发布时间】:2015-08-25 09:01:44
【问题描述】:

我有一个绑定到ViewModel 类的UserControl

我还有一个包含Command 用于关闭窗口的类。

在我的UserControl 中,我有两个按钮:SaveCancel

我的 Cancel 按钮绑定到 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 而不是窗口。

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

【问题讨论】:

    标签: c# wpf button binding command


    【解决方案1】:

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

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

    并将其发送到Execute 方法。

    CommonCommands.CloseWindow.Execute(parameter);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多