Note that there are some explanatory texts on larger screens.

plurals
  1. POChanging Data Context for Data Template clears Combo Box selection
    text
    copied!<p>I have a TreeView that permits the user to select different items. The display for each item is determined using Data Templates with the DataType set to the appropriate ViewModel type. The DataContext is automatically set based on the selected item in the tree view to the appropriate ViewModel.</p> <p><strong>Here's the problem:</strong></p> <p>One of the DataTemplates has a ComboBox bound to an ObservableCollection to get the list of items and a property to get/set the SelectedValue in the ViewModel.</p> <p>When I select one item of this type, and then select another item of the same type, the ComboBox displays blank instead of the correct selected item. It appears that the Combo Box is setting the SelectedValue property to <em>NULL</em> immediately after the transition to the new item, and then never updating.</p> <pre><code>&lt;ComboBox Margin="1,0" ItemsSource="{Binding ItemsToSelect}" SelectedValue="{Binding SelectedValue}" SelectedValuePath="ValuePath" DisplayMemberPath="DisplayPath" IsEnabled="{Binding CanSelectItem}"&gt; &lt;/ComboBox&gt; </code></pre> <p>The really strange part is if I select an item of a different type between selecting items of the same type, it always displays correctly.</p> <p>I've tried ignoring the <em>NULL</em> value in the SelectedValue setter, and that didn't work regardless of whether I also raised the PropertyChanged event or not.</p> <pre><code>private MyObject selectedValue; public MyObject SelectedValue { get { return selectedValue; } set { if (value != null) { this.selectedValue = value; } this.OnPropertyChanged("SelectedValue"); } } </code></pre> <p>Looking at the similar questions while writing this lead me to an interesting attribute that I hadn't found yet - <code>IsSynchronizedWithCurrentItem</code> from this <a href="https://stackoverflow.com/questions/4657028/wpf-combo-box-weird-problem">question</a>. At first, I thought this solved the problem, but alas it just changes the behavior somewhat.</p> <p>With this attribute set to <code>True</code>, the combo doesn't <em>entirely</em> clear its selection, but instead just marks the first item as selected. So, instead of being set to <em>NULL</em>, now the SelectedValue property is being set to the first item in the list.</p> <p>Anyone have any ideas for a solution?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload