gpt4 book ai didi

c# - WPF:更改 ComboBox 的 ItemTemplate 会移除在您键入时向下跳转列表的功能。有任何解决这个问题的方法吗?

转载 作者:可可西里 更新时间:2023-11-01 08:56:53 28 4
gpt4 key购买 nike

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>
<ComboBox Height="23" Width="300"
ItemsSource="{Binding Path=Objects}"
DisplayMemberPath="Name"
>
</ComboBox>
</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>
<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 时,它​​会失去该功能。有没有另一种方法来绑定(bind)我需要的东西并保留该功能或重新启用它?也许 ItemTemplate 设置错误?

最佳答案

查看我对这个问题的回答:Can I do Text search with multibinding

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

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

<ComboBox ...
IsTextSearchEnabled="True">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

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

调用 OnPropertyChanged 以获取 NameAndId
<ComboBox ...
TextSearch.TextPath="NameAndId"
IsTextSearchEnabled="True">


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

关于c# - WPF:更改 ComboBox 的 ItemTemplate 会移除在您键入时向下跳转列表的功能。有任何解决这个问题的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4960222/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com