I have a MainWindow.xaml that gets populated with UserControls. I have a control in the MainWindow.xaml that has a button. The button is bound to the following command in MyViewModel.cs:
public ICommand MyCommand
{
get
{
return Get(() => MyCommand, () => new RelayCommand(ExecuteMyCommand, CanExecuteMyCommand));
}
}
public void ExecuteMyCommand()
{
Messenger.Default.Send(new NotificationMessage(this, MainWindowMessageBus.ShowPopup1), MainWindowMessageBus.Token);
Method1();
Messenger.Default.Send(new NotificationMessage(this, MainWindowMessageBus.ShowPopup2), MainWindowMessageBus.Token);
Method2();
}
public bool CanExecuteInsertBedCommand()
{
return true;
}
Method1() and Method2() execute code that take about 5 seconds each. The messengers are sending messages to the codebehind MainWindow.xaml.cs:
Popup1 popup1;
Popup2 popup2;
private void NotificationMessageReceived(NotificationMessage msg)
{
switch(msg.Notification)
{
case MainWindowMessageBus.ShowPopup1:
popup1 = new Popup1();
ControlContainer.Children.Add(popup1);
break;
case MainWindowMessageBus.ShowPopup2:
// Remove popup1
ControlContainer.Children.Remove(popup1);
popup1 = null;
// Add popup2
popup2 = new Popup2();
ControlContainer.Children.Add(popup2);
break;
default:
break;
}
}
Expected results: upon pressing my button, Popup1 shows immediately and stays in the window while Method1() executes. Then, Popup2 replaces Popup1 in the window and Method2() executes.
Actual results: upon pressing my button, nothing happens in the UI. Method1() and Method2() execute as expected, and after they both run (~10 seconds), Popup2 is displayed. I never see Popup1.
I tried a couple threading/async methods, but they didn't work. How can I get ExecuteMyCommand() to update the UI as it goes?
EDIT
Ok so I can't answer my own question for some reason. I don't think this question is a duplicate of the specified thread, since that would imply that I already knew I needed to run Method1() in the background, which I did not. Anyways, here's what I changed:
public async void ExecuteMyCommand()
{
Messenger.Default.Send(new NotificationMessage(this, MainWindowMessageBus.ShowPopup1), MainWindowMessageBus.Token);
await Task.Run(() =>
{
Method1();
});
Messenger.Default.Send(new NotificationMessage(this, MainWindowMessageBus.ShowPopup2), MainWindowMessageBus.Token);
Method2();
}