在显示两列的 WPF 组合框中搜索
本文关键字:组合 WPF 搜索 两列 显示 | 更新日期: 2023-09-27 18:37:12
我必须在WPF comboBox中启用搜索,在我的WPF MVVM应用程序中显示两列。
下面是我的代码,它显示两列,例如: 名字 - 姓氏
<ComboBox Grid.Column="3" Grid.Row="15" Height="Auto" HorizontalAlignment="Stretch"
Name="cmbName" VerticalAlignment="Stretch"
SelectedItem="{Binding Name, Mode=TwoWay}"
ItemsSource="{Binding GetAllName}"
IsTextSearchEnabled="True">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock DataContext="{Binding}">
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} - {1}">
<Binding Path="FirstName" />
<Binding Path="LastName" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
我认为在这种情况下,IsTextSearchEnabled没有发挥任何作用。
对此有任何帮助吗?
您可以使用 TextSearch.TextPath。
<ComboBox Grid.Column="3" Grid.Row="15" Height="Auto" HorizontalAlignment="Stretch"
Name="cmbName" VerticalAlignment="Stretch"
SelectedItem="{Binding Name, Mode=TwoWay}"
ItemsSource="{Binding GetAllName}">
<TextSearch.TextPath>FirstName</TextSearch.TextPath>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock DataContext="{Binding}">
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} - {1}">
<Binding Path="FirstName" />
<Binding Path="LastName" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
你似乎有些困惑。首先,您不是在ComboBox
中显示两列,而是显示两个字段值...也许你应该编辑你的误导性标题?
其次,我不相信你完全了解IsTextSearchEnabled
属性的用途。但是,您是正确的,使用此属性一事无成。从 MSDN 上的"ItemsControl.IsTextSearchEnabled
属性"页:
获取或设置一个值,该值指示是否在 ItemsControl 实例上启用文本搜索。
从 MSDN 上的"TextSearch
类"页:
此类用于将字符串分配给控件集合中的项。为集合中的每个项分配一个字符串可实现两个目标。它指定选择项时要显示的文本,并使用户能够通过键入分配的字符串来选择项。
例如,假设 ComboBox 包含 Image 对象的集合,其中一个对象是狗的图像。如果将字符串"Dog"分配给该项,则用户可以通过在组合框的文本框中键入单词来选择狗。一旦用户键入足够的单词以将其与选择中的其他项目区分开来,就会选择狗的图像。如果在组合框上将 IsEditable 设置为 true,则文本框中将显示"Dog"。
可以通过对控件使用 TextSearch.TextPath 属性或通过在控件集合中的每个项上设置 Text 属性来指定标识项的文本。设置这些属性之一可确保不会显示意外的文本。如果在控件的集合项上设置 Text 属性,则将忽略 TextPath 属性。如果将 TextPath 属性设置为不是实际属性名称的值,则会忽略 TextPath。