0

I have a WPF control inheriting from ComboBox whose ItemsSource is bound to a list of elements, and whose SelectedItem is bound to another field. I have two references to the same list in my application: one resides in my MainWindow class, and one resides in my App class.

The list of elements used as the ItemsSource is assigned to the ComboBox at the time it is created. Thus, I expect to get an ItemsSourceChanged event.

The strange thing is, if the ItemsSource is bound to the MainWindow's list, then the ComboBox becomes populated with the correct SelectedItem drawn from the bound field. However, if I bind the ItemsSource to the App's copy of the list, then the SelectedItem becomes overwritten with null due to the ItemsSourceChanged event.

Here is the XAML for the ComboBox when it's binding to the App copy of the list:

<local:TagSelectionComboBox FilteredTagsList="{Binding Path=TagsList, Source={x:Static Application.Current}}" SelectedItem="{Binding TagValue}"></local:TagSelectionComboBox>

Here is the XAML for the ComboBox when it's binding to the MainWindow copy of the list:

<local:TagSelectionComboBox FilteredTagsList="{Binding TagsList, RelativeSource={RelativeSource AncestorType=Window}}" SelectedItem="{Binding TagValue}"></local:TagSelectionComboBox>

Here is the MainWindow's property used for binding:

public ObservableCollection<Tag> TagsList
{
    get { return proj.Sim.Tags; }
}

And here is the App's property used for binding:

public ObservableCollection<Tag> TagsList
{
    get { return proj.Sim.Tags; }
}

So these two properties on App and MainWindow are returning the same list. Stepping through in the debugger confirms: proj.Sim.Tags contains the same list in both cases.

Why does changing from one binding source to another alter the binding behavior? Is something else going on?

I've found that if I explicitly set IsSynchronizedWithCurrentItem="True", then the behavior is the same in both cases. So it's almost like IsSynchronizedWithCurrentItem="True" is the default behavior when I use the MainWindow (RelativeSource) binding but IsSynchronizedWithCurrentItem="False" is the default behavior when I use the App (x:Static) binding.

Background: the ComboBox-derived control in this question is basically the same as YantingChen's answer for this question:

Dynamic filter of WPF combobox based on text input

afarley
  • 781
  • 6
  • 26
  • The SelectedItem must refer to an item that must be contained in the ItemsSource (same instance). – BionicCode Nov 03 '22 at 09:46
  • IsSynchronizedWithCurrentItem is only relevant when you want to synchronize the current collection view with the SelectedItem of the collection source. Otherwise the view won't track the selected items. – BionicCode Nov 03 '22 at 09:48

0 Answers0