WPF:更改ComboBox的ItemTemplate会删除在键入时跳转列表的function。 有任何解决这个问题的方法吗?

PersonVM.cs

public class MainWindowVM { public MainWindowVM() { PersonList = new ObservableCollection(Employees); } private Person[] Employees = new Person[] { new Person { ID = 1, Name = "Adam" }, new Person { ID = 2, Name = "Bill" }, new Person { ID = 10, Name = "Charlie" }, new Person { ID = 15, Name = "Donna" }, new Person { ID = 20, Name = "Edward" } }; public ObservableCollection PersonList { get; set; } } 

Person.cs

 public class Person { public string Name { get; set; } public int ID { get; set; } } 

MainWindow.xaml (function正常的版本 – 不是我想要显示的)

       

MainWindow.xaml (正确显示 – 无法正常运行)

                   

第二个代码显示我希望ComboBox显示{ID} | {Name} {ID} | {Name} ,但它消除了ComboBox的常见function。 在第一个示例中,当选择ComboBox时,用户可以开始键入它并让它向下跳转列表。 例如,如果按下字母A,它会跳转到“Adam”,B会跳转到“Bill”等。这就是ComboBox的运行方式。 但是,当我覆盖ComboBox ItemTemplate时,它会丢失该function。 是否有另一种方法来绑定我需要的东西并保留该function或重新启用它? 也许ItemTemplate设置错了?

请参阅我对此问题的回答: 我可以使用多重绑定进行文本搜索

遗憾的是TextSearch.Text在DataTemplate中不起作用。 我想你有两种选择

选项1 。 将ComTeBox的IsTextSearchEnabled设置为True,覆盖源类中的ToString并将TextBlock中的MultiBinding更改为Binding

        public class Person { public override string ToString() { return String.Format("{0} | {1}", Name, ID); } public string Name { get; set; } public int ID { get; set; } } 

选项2 。 在源类中创建一个新属性,其中组合了TextSearch.TextPath名称和ID。 此外,只要为NameID执行此操作,就应该为NameAndId调用NameAndId

  public string NameAndId { return String.Format("{0} | {1}", Name, ID); }