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; }
}
人物.cs
public class Person
{
public string Name { get; set; }
public int ID { get; set; }
}
主窗口.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>
<ComboBox Height="23" Width="300"
ItemsSource="{Binding Path=Objects}"
DisplayMemberPath="Name"
>
</ComboBox>
</Grid>
</Window>
主窗口.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>
<ComboBox Height="23" Width="300"
ItemsSource="{Binding Path=Objects}"
>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock DataContext="{Binding}">
<TextBlock.Text>
<MultiBinding StringFormat="{} {0} | {1}">
<Binding Path="ID" />
<Binding Path="Name" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</Window>
第二个代码显示我希望 ComboBox 显示的内容{ID} | {Name}
,但是它剥夺了 ComboBox 的一个常用功能。在第一个示例中,当选择 ComboBox 时,用户可以开始在其中键入内容并使其在列表中向下跳转。例如,如果您按字母 A,它会跳转到“Adam”,B 会跳转到“Bill”,等等。这就是 ComboBox 的工作原理。但是,当我覆盖 ComboBox ItemTemplate 时,它会失去该功能。是否有另一种方法可以绑定我需要的内容并保留该功能或重新启用它?也许 ItemTemplate 设置错误?