我有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
而不是窗口。
有没有办法实现我想要做的事情?
答案 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();