【问题标题】:AutoCompleteBox issue when having multiple items with same values具有相同值的多个项目时出现 AutoCompleteBox 问题
【发布时间】:2011-03-02 13:36:48
【问题描述】:

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

【问题讨论】:

  • 用户如何能够在这里分辨出不同之处?
  • 是的,我认为如果您能描述用户应该如何从相同值的列表中进行选择,那将会很有帮助。
  • 除非我们得到更多信息,否则很难说清楚。但如果我理解正确,这里的代码 ValueMemberPath="Name" 应该是 ValueMemberPath="ID"
  • @Lasse:用户能够分辨出区别,因为我将 SelectedPerson 绑定到另一个控件。这只是一个例子(我同意这是一个糟糕的例子)。 @ingo:如果我设置 ValueMemberPath="ID" 那么 ID 将显示在我的 AutoCompleteBox 中。问题是,它实际上第一次设置了正确的 SelectedPerson,但随后又将其设置为 ObservableCollection 中的第一个。

标签: c# .net wpf autocompletebox


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多