Update
After a bit of investigating. What seems to be the issue is that the SelectedValue/SelectedItem is occurring before the Item source is finished loading. If I sit in a break point and wait a few seconds it works as expected. Don't know how I'm going to get around this one.
End Update
I have an application using in WPF using MVVM with a ComboBox. Below is the ViewModel Example. The issue I'm having is when we leave our page and migrate back the ComboBox is not selecting the current Value that is selected.
View Model
public class MyViewModel
{
private MyObject _selectedObject;
private Collection<Object2> _objects;
private IModel _model;
public MyViewModel(IModel model)
{
_model = model;
_objects = _model.GetObjects();
}
public Collection<MyObject> Objects
{
get
{
return _objects;
}
private set
{
_objects = value;
}
}
public MyObject SelectedObject
{
get
{
return _selectedObject;
}
set
{
_selectedObject = value;
}
}
}
For the sake of this example lets say MyObject has two properties (Text and Id). My XAML for the ComboBox looks like this.
XAML
<ComboBox Name="MyComboBox" Height="23" Width="auto"
SelectedItem="{Binding Path=SelectedObject,Mode=TwoWay}"
ItemsSource="{Binding Objects}"
DisplayMemberPath="Text"
SelectedValuePath="Id">
No matter which way I configure this when I come back to the page and the object is reassembled the ComboBox will not select the value. The object is returning the correct object via the get in the property though.
I'm not sure if this is just an issue with the way the ComboBox and MVVM pattern works. The text box binding we are doing works correctly.
In this case, the selecteditem bind doesn't work, because the hash id of the objects are different.
One possible solution is:
Based on the selected item id, recover the object on the itemsource collection and set the selected item property to with it.
Example:
The Property binded to ItemSource is:
The property binded to SelectedItem is:
The recovery code is:
I hope it helps you. I spent a lot of my time searching for answers, but I couldn´t find.
IsSyncronizedWithCurrent=False will make it work.
Setting
IsSynchronizedWithCurrentItem="True"
worked for me!ComboBox.SelectionBoxItem.ToString()
Use Loaded event:
It works for me.
I was fighting with this issue for a while. In my case I was using in complex type (List) as the Item Source and was using a KeyType as the selected value. On the load event, the KeyType was getting set to null. This caused everything to break. None of the sub elements would get updated when the key changed. It turned out that when I added a check to make sure the proposed value for KeyType was not null, everything worked as expected.