Reputation: 217
I have a generic modal dialog view, which is getting called from viewmodels like below:
NotificationMessageViewModel vm = new NotificationMessageViewModel()
{
MessageContent = jobExistMsg,
MessageHeader = "Warning",
MessageType = NotificationMessageType.Warning,
Type = ModalType.OkCancel
};
mainEntity.ModalContent = vm;
vm.CloseRequested += ImportJobConfirmation_CallBack;
The issue with this approach is, I cannot use this code inside while
loop since the code execution ignores the CloseRequested
event. The current workaround is, I have callback function for CloseRequested
and I call the same function again inside callback
function for other items in loop. So its kind of recursive calling.
Is there any better solution to handle this situation?
I have edited the code a little. Say I have 10 records, I want this modal popup for every record that exists while processing in loop. If I will write this code inside a while loop, I will see only one pop-up for 10 records and the close request will be fired only once, where as I should get the modal for every existing record(say 5 existing records).
Upvotes: 0
Views: 305
Reputation: 32627
You can use an async / await
combination to get what you want. I have just implemented this with a plain window, but you could easily adapt it to use the view model.
In the secondary window (the view model in your case), provide an awaitable method to display the window:
public partial class Window1 : Window
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
public Window1()
{
InitializeComponent();
this.Closed += Window1_Closed;
}
void Window1_Closed(object sender, EventArgs e)
{
tcs.SetResult(null);
}
public async Task ShowAsync()
{
Show();
await tcs.Task;
}
}
Then in the calling window, you can successively show any number of windows and wait for them to close like so:
async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 10; ++i)
{
var secondaryWindow = new Window1();
await secondaryWindow.ShowAsync();
}
}
If you like, you could also expose the tcs.Task
in a property of Window1
. This would allow you more flexibility. E.g.:
var secondaryWindow = new Window1();
secondaryWindow.Show();
await secondaryWindow.WaitForCloseTask;
where
//Window1
public Task WaitForCloseTask { get { return tcs.Task; } }
Upvotes: 2