With the following code I expect the combobox to revert back to the initial Selected_Item, however it does not, the ComboBox on the window always shows any new item I select (and gets out of sync with the model), i also tried to call always the OnPropertyChanged("Selected_Item"); no matter whether the value is different, and still the combobox shows the newly selected item and gets out of sync. Probably i am doing it the wrong way, however, what would be the correct way?
namespace WpfApplication8
{
public class Context : INotifyPropertyChanged
{
#region Privates
bool c_Disabled = false;
#endregion
#region Ctors
public Context()
{
Items = new List<MyItem>();
Items.Add(new MyItem("Item 1"));
Items.Add(new MyItem("Item 2"));
Items.Add(new MyItem("Item 3"));
Selected_Item = Items[0];
c_Disabled = true;
}
#endregion
#region Properties
public List<MyItem> Items
{
get;
private set;
}
private MyItem c_Selected_Item;
public MyItem Selected_Item
{
get { return c_Selected_Item; }
set
{
if (c_Selected_Item != value)
{
if (!c_Disabled)
{
c_Selected_Item = value;
OnPropertyChanged("Selected_Item");
}
}
}
}
#endregion
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string f_Prop_Name)
{
PropertyChangedEventHandler l_Handler = PropertyChanged;
if(null != l_Handler)
{
l_Handler(this, new PropertyChangedEventArgs(f_Prop_Name));
}
}
#endregion
}
public class MyItem
{
public MyItem(string f_Name)
{
Name = f_Name;
}
public string Name {get;set;}
}
}
and the following window:
<Window x:Class="WpfApplication8.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">
<Grid>
<ComboBox
HorizontalAlignment="Center"
VerticalAlignment="Top"
ItemsSource="{Binding Items}"
SelectedItem="{Binding Selected_Item}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</Window>