I'm having a struggle with a ComboBox in a WPF app. It's similar to some other questions but the classic solution to this problem don't appear to be working.
Essentially, it's the same problem as this:
WPF ComboBox SelectedItem Set to Null on TabControl Switch
However, my ItemsSource is already in the XAML after the SelectedItem, which is what normally sorts this out.
What is happening is that I have the a view with the combobox on it with data already loaded then an event is fired that updates the data feeding into the ComboBox. The ViewModel consumes the event (fired by a BackgroundWorker that gets the data) and updates its ObservableCollection that is the ItemsSource with the new data. Like this:
int id = (int)Invoice.Customer.DatabaseID;
Customers = new ObservableCollection<Customer>(customers);
Invoice.Customer = Customers.FirstOrDefault(x => x.DatabaseID == id);
As you can see it attempts to set the Customer on the Invoice back to what it was originally. This does occur, observed with a break point, however, as soon as this is completed the Customer gets set back to null from an unidentified source (none of my code appears in the call stack, it's all framework stuff).
The XAML for the ComboBox is this:
<ComboBox DisplayMemberPath="AccountCode"
SelectedItem="{Binding Invoice.Customer, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
ItemsSource="{Binding Customers}"/>
So to summarise, my ComboBox SelectedItem gets set to null after the ItemsSource is updated and ensuring ItemsSource is after SelectedItem does nothing. I really can't figure out why it's getting set to null and I'm not sure where to look. Any pointers or things I can look at in order to find a solution to this would be greatly appreciated.
EDIT: Ok, I've been playing with it a bit more and I suspect it has something to do with the update coming from a BackgroundWorker. I use a Timer and a BackgroundWorker in my data service to periodically update the customer list from the database to ensure the data is relatively current. The BackgroundWorker fires an event when it is finished to inform interested objects that the list has been updated. This appears to mean that when the events are consumed they are in a different thread. When it updates this way the SelectedItem gets set to null after I set it to the correct item and therefore sets Invoice.Customer to null. I quickly added a button to my view to update the customers without using the BackgroundWorker and this appears to work every time. I'd like to keep updating the data periodically but I need to figure this out before I can do so.