I have a ComboBox whose properties ItemsSource and SelectedValue are model bound. Sometimes a model needs to set the selected item to another, but when I do this in the model, the model value is not reflected in the view, even if the selected value is correctly set (marked with both snoop and SelectionChanged event handler).
To illustrate the problem, here is a simple xaml:
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Self}}"> <Grid> <ComboBox Height="25" Width="120" SelectedValue="{Binding SelectedValue}" SelectedValuePath="Key" ItemsSource="{Binding PossibleValues}" DisplayMemberPath="Value"/> </Grid> </Window>
And here is the model:
using System.Collections.Generic; using System.Windows; using System.ComponentModel; namespace WpfApplication1 { public partial class MainWindow : Window, INotifyPropertyChanged { int m_selectedValue = 2; Dictionary<int, string> m_possibleValues = new Dictionary<int, string>() { { 1, "one" }, { 2, "two" }, { 3, "three" }, {4,"four"} }; public int SelectedValue { get { return m_selectedValue; } set { if (value == 3) { m_selectedValue = 1; } else { m_selectedValue = value; } PropertyChanged(this, new PropertyChangedEventArgs("SelectedValue")); } } public Dictionary<int, string> PossibleValues { get { return m_possibleValues; } set { m_possibleValues = value; } } public MainWindow() { InitializeComponent(); } public event PropertyChangedEventHandler PropertyChanged; } }
I expected the behavior to be as follows:
- Two are selected first
- Choose "one" -> ComboBox will display "one"
- Choose two -> ComboBox will display two
- Choose βthreeβ β βComboboxβ displays β one β
- Choose "four" β ComboBox will display "four"
However, in No. 4, βthreeβ is displayed. What for? The value in the model has been changed to 1 ("one"), but 3 ("three") is still displayed in the view.
I found a workaround by explicitly updating the binding target in the SelectionChanged event handler, but this seems to be wrong. Is there any other way to achieve this?
source share