I have a ListBox in WPB bound to an ObservableCollection
public static readonly DependencyProperty ProgramsProperty =
DependencyProperty.Register("Programs",
typeof(ObservableCollection<ProgramData>), typeof(ProgramView),
new PropertyMetadata(default(ObservableCollection<ProgramData>)));
public ObservableCollection<ProgramData> Programs
{
get { return (ObservableCollection<ProgramData>)GetValue(ProgramsProperty); }
set { SetValue(ProgramsProperty, value); }
}
and the selected element of the ListBox bound to one element
public static readonly DependencyProperty SelectedProgramProperty =
DependencyProperty.Register("SelectedProgram",
typeof(ProgramData), typeof(ProgramView),
new PropertyMetadata(default(ProgramData)));
public DispenserInfo SelectedProgram
{
get { return (ProgramData)GetValue(SelectedProgramProperty); }
set { SetValue(SelectedProgramProperty, value); }
}
When the user changes the selected element in the ListBox I would like to check the status of the "old" selected element - maybe we need to save the old element - and react in some way.
So I would like to something like this
public static bool UpdateCallback(ProgramData oldVal, ProgramData newVal)
{
if (oldVal.DataChanged == false)
return true;
var res = MessageBox.Show("Save or discard changes", "Question",
MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
switch (res)
{
case MessageBoxResult.Yes:
oldVal.Save();
return true;
case MessageBoxResult.No:
oldVal.Discard();
return true;
case MessageBoxResult.Cancel:
return false;
}
return true;
}
I there a way to do this with validation/coercing callbacks?
Update:
As Oliver and Sheridan suggested I tried the changed as well as the coerce callback and this is working quite well to do some tasks in between clicking and refreshing the UI. But when I try to cancel the update in the coerceCallback like this
private static object CoerceValueCallback(DependencyObject dependencyObject, object baseValue)
{
var @this = (ProgramView)dependencyObject;
var res = MessageBox.Show("Save or discard changes", "Question", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);
switch (res)
{
case MessageBoxResult.Cancel:
return @this.SelectedProgram;
}
return baseValue;
}
the UI stays at the old values as expected but the ListBox highlights the wrong line - the one the user has clicked and not the one from the binding when canceled in the coerceCallback. Do I need to update the binding manually? Any ideas