I have a combo box for which I change the values of the selected items in the bound property setter. The value is not reflected in the combobox in View. When I select 2 in UI, it should show 3 but it shows 2. I don't understand why it doesn't work even though I set the updatesourcetrigger to Propertychanged.
public class MyViewModel : INotifyPropertyChanged
{
private int _selected;
public List<int> MyList => new List<int>() {1, 2, 3};
public int Selected
{
get => _selected;
set
{
_selected = value;
if (value == 2)
_selected = 3;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
and my view is
<Window x:Class="WpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel VerticalAlignment="Center">
<ComboBox Height="50" Width="200" ItemsSource="{Binding MyList}" SelectedItem="{Binding Selected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ></ComboBox>
</StackPanel>
However, I noticed that if I add a Delay or change UpdateSourceTrigger to LostFocus, it works fine. Can anyone explain why it doesn't work in the first case even if propertychanged is fired from source to target?
Code with a delay which works
<ComboBox Height="50" Width="200" ItemsSource="{Binding MyList}" SelectedItem="{Binding Selected,Mode=TwoWay,Delay=1}" ></ComboBox>
Also out of curiosity I added a textbox to my view ,binded the same with selecteditem with same updatesourcetrigger. But to my surprise when I enter 2 in textbox,it changes to 3 and updates combobox too.I find it difficult to understand why this doesnt work witn combobox?
<StackPanel VerticalAlignment="Center">
<ComboBox Height="50" Width="200" ItemsSource="{Binding MyList}" SelectedItem="{Binding Selected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ></ComboBox>
<TextBox Height="50" Width="200" Text="{Binding Selected,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ></TextBox>
</StackPanel>