C# · 12月 27, 2021

c# – WPF:更改ComboBox的ItemTemplate可以删除在输入时跳过列表的功能.任何方法来解决这个问题?

PersonVM.cs public class MainWindowVM{ public MainWindowVM() { PersonList = new ObservableCollection<Person>(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<Person> PersonList { get; set; }}

Person.cs

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

MainWindow.xaml(功能工作版本 – 不是我想要显示)

<Window x:Class=”TestApp.MainWindow” xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”> <Grid> <Combo@R_279_2419@ Height=”23″ Width=”300″ ItemsSource=”{Binding Path=Objects}” DisplayMemberPath=”Name” > </Combo@R_279_2419@> </Grid></Window>

MainWindow.xaml(正确显示 – 无法正常工作)

<Window x:Class=”TestApp.MainWindow” xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”> <Grid> <Combo@R_279_2419@ Height=”23″ Width=”300″ ItemsSource=”{Binding Path=Objects}” > <Combo@R_279_2419@.ItemTemplate> <DataTemplate> <TextBlock DataContext=”{Binding}”> <TextBlock.Text> <MultiBinding StringFormat=”{} {0} | {1}”> <Binding Path=”ID” /> <Binding Path=”Name” /> </MultiBinding> </TextBlock.Text> </TextBlock> </DataTemplate> </Combo@R_279_2419@.ItemTemplate> </Combo@R_279_2419@> </Grid></Window>

第二个代码显示了我想要的组合框显示{ID} | {Name},但它消除了Combo@R_279_2419@的一个常用功能.在第一个例子中,当选择Combo@R_279_2419@时,用户可以开始输入它并让它从列表中跳下来.例如,如果按字母A,它跳转到“Adam”,B跳转到“Bill”等.这是Combo@R_279_2419@应该如何运作.但是,当我重写Combo@R_279_2419@ ItemTemplate时,它会丢失该功能.是否有另一种方式来绑定我需要的东西,并保持该功能或重新启用? ItemTemplate也许设置错误?

解决方法 看到我对这个问题的回答: Can I do Text search with multibinding

不幸的是,TextSearch.Text在DataTemplate中不起作用.我想你有两个选择

选项1.将Combo@R_279_2419@的IsTextSearchEnabled设置为True,覆盖源类中的ToString,并将TextBlock中的MultiBinding更改为绑定

<Combo@R_279_2419@ … IsTextSearchEnabled=”True”> <Combo@R_279_2419@.ItemTemplate> <DataTemplate> <TextBlock Text=”{Binding}”/> </DataTemplate> </Combo@R_279_2419@.ItemTemplate></Combo@R_279_2419@> 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.在源类中创建一个新的Property,您可以将TextSearch.TextPath的Name和ID组合在一起.此外,只要您为Name或ID进行操作,您应该为NameAndId调用OnPropertyChanged

<Combo@R_279_2419@ … TextSearch.TextPath=”NameAndId” IsTextSearchEnabled=”True”>public string NameAndId{ return String.Format(“{0} | {1}”,ID);}