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

时间:2015-06-10 08:14:46

标签: c# wpf button binding command

我有UserControl绑定到ViewModel类。

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

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

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

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

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

1 个答案:

答案 0 :(得分:2)

只需将CommandParameter发送给CloseCommand,就像您已为CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" 所做的那样。

Execute

并将其发送到CommonCommands.CloseWindow.Execute(parameter); 方法。

QNetworkRequest req(url);
QScopedPointer<QNetworkReply> reply(nam.get(req));

QTime timeout= QTime::currentTime().addSecs(10);
while( QTime::currentTime() < timeout && !reply->isFinished()){
    QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

if (reply->error() != QNetworkReply::NoError) {
    qDebug() << "Failure" <<reply->errorString();
}
QByteArray data = reply->readAll();