Reputation: 19353
I have a ListBox bound to an ObservableCollection
of objects. Selecting object loads it into the UI for editing and saving.
I would like that when selecting a new object in the ListBox that there is a prompt if there is unsaved changes UI so a check needs to occur when the ListBox selection changes and a prompt appears to confirm the change - if the change is confirmed then it happens as normal otherwise the change is prevented/undone.
The prompt code is an async
method that returns a Task and so it cannot occur in a setter - it can occur in an event though which I have had limited success with.
It seems we only have access to SelectionChanged
event. I can prompt here but when reverting the SelectionChanged
event is fired again to result in an infinite loop.
Given that this is probably quite a common pattern - what is the best practice way to handle this?
Upvotes: 2
Views: 292
Reputation: 69959
Add a method that calls your prompt code as you call it and then returns the value. After that, you can simply call that method from the setter of the property that is data bound to the SelectedItem
property:
public YourDataType CurrentItem
{
get { return currentItem; }
set
{
if (isChangeConfirmed)
{
isChangeConfirmed = false;
currentItem = value;
NotifyPropertyChanged("CurrentItem");
}
else GetIsChangeConfirmed(value);
}
}
public async void GetIsChangeConfirmed(object value)
{
isChangeConfirmed = await YourAsyncPromptMethod();
if (isChangeConfirmed) CurrentItem = value;
}
private bool isChangeConfirmed = false;
UPDATE >>>
Actually, as you correctly pointed out, there are some restrictions over the use of async
methods. To get around that, you can set the confirmation value to a variable that you check inside the setter as shown above, instead of returning it from the method.
Upvotes: 1