3

我的问题是,如果我在 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 个项目。现在,当我选择第四个时,它被选中并且绑定更新。然而,它会回到第一个项目。这是一个错误还是预期的行为,任何人都可以帮助我解决这个问题吗?

4

1 回答 1

1

我有同样的问题。我还没有尝试过,但我找到了这个链接,它看起来有解决方案。
http://www.yumasoft.com/node/45

编辑
我刚刚确认这确实有效。

对于询问用户如何区分的评论。ItemTemplate 提供了比仅在 TextBox 部分中显示的更多详细信息。这允许用户决定使用哪个记录。

于 2011-09-30T17:32:11.433 回答