Under certain conditions if the user selects an item in a combobox, it automatically must be changed to another item
ViewModel
public class VM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
private string selected;
public string Selected
{
get { return selected; }
set
{
if (selected != value)
{
selected = value;
OnPropertyChanged("Selected");
}
}
}
private ObservableCollection<string> collection;
public ObservableCollection<string> Collection
{
get { return collection; }
set
{
collection = value;
OnPropertyChanged("Collection");
}
}
public VM()
{
this.Collection = new ObservableCollection<string>(new string[] { "A", "B", "C" });
this.Selected = "A";
this.PropertyChanged += VM_PropertyChanged;
}
void VM_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
this.Selected = "C";
}
}
View
<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">
<StackPanel>
<Grid>
<ComboBox ItemsSource="{Binding Collection}" SelectedValue="{Binding Selected}"/>
</Grid>
<Label Content="{Binding Selected, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
</Window>
So, in this example, no matter what do I select, it should show "C" both, on the combobox and Label, but "C" only shows on Label, it means that the ViewModel is updated but not the view.
It seems the problem here is to try to change the property from the PropertyChanged method.
What could be wrong?