我有一个组合框,可以更改绑定属性设置器中所选项目的值。该值未反映在View的组合框中。当我在UI中选择2时,它应该显示3,但显示2。 我不明白为什么即使将updatesourcetrigger设置为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));
}
}
我的观点是
<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>
但是,我注意到,如果添加一个Delay或将UpdateSourceTrigger更改为LostFocus,它会很好地工作。 谁能解释为什么即使从源头到目标触发了属性更改,在第一种情况下它也不起作用?
延迟有效的代码
<ComboBox Height="50" Width="200" ItemsSource="{Binding MyList}" SelectedItem="{Binding Selected,Mode=TwoWay,Delay=1}" ></ComboBox>
出于好奇,我还在视图中添加了一个文本框,将其与带有相同updatesourcetrigger的selecteditem绑定在一起。但是令我惊讶的是,当我在文本框中输入2时,它也变为3并更新了组合框。我很难理解为什么在组合框中不起作用?
<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>