我的问题是,如果我在 ValueMemberPath 中有具有相同值的对象,那么 AutoCompleteBox 在选择正确的项目后会选择第一个项目。我已将 SelectedItem 绑定到一个属性,如果有多个具有相同值的项目,我可以看到它会被触发两次。
我已将 AutoCompleteBox 绑定到 Person 对象的 ObservableCollection。
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public string FullName
{
get
{
return Name + " - " + ID;
}
}
}
我的 XAML 看起来像这样:
<StackPanel>
<inputtoolkit:AutoCompleteBox x:Name="autoCompleteBox" ValueMemberPath="Name" ItemsSource="{Binding Persons}" SelectedItem="{Binding SelectedPerson, Mode=TwoWay}">
<inputtoolkit:AutoCompleteBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding FullName}" FontSize="14" FontWeight="Bold"></TextBlock>
</DataTemplate>
</inputtoolkit:AutoCompleteBox.ItemTemplate>
</inputtoolkit:AutoCompleteBox>
<TextBlock x:Name="textBlock" Text="{Binding SelectedPerson.ID}"></TextBlock>
</StackPanel>
我的 Window_Loaded 看起来像这样:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Persons = new ObservableCollection<Person>();
Persons.Add(new Person() { ID = 1, Name = "Person" });
Persons.Add(new Person() { ID = 2, Name = "Person" });
Persons.Add(new Person() { ID = 3, Name = "Person" });
Persons.Add(new Person() { ID = 4, Name = "Person" });
autoCompleteBox.DataContext = this;
textBlock.DataContext = this;
}
当我写“Per”时,下拉菜单中将显示 4 个项目。现在,当我选择第四个时,它被选中并且绑定更新。然而,它会回到第一个项目。这是一个错误还是预期的行为,任何人都可以帮助我解决这个问题吗?