如何通过在WPF组合框中键入键盘字母键来选择项目?

问题描述 投票:0回答:4

我有一个 WPF

ComboBox
,当我键入该字母时,我想转到
ComboBox
中以(例如)“e”开头的项目。怎么办?

我的XAML代码:

<ComboBox ItemsSource="{Binding Roles}" SelectedValuePath="Id"
          ItemTemplate="{StaticResource ComboBoxDisplayName}"
          SelectedItem="{Binding SelectedRole}"
          Width="150"/> 
wpf select combobox hotkeys
4个回答
26
投票

编辑:我猜你有一个

ItemTemplate
,看起来有点像这样:

<StackPanel>
    <TextBlock Text="{Binding Path=Foo}" />
    <TextBlock Text="{Binding Path=Bar}" />
</StackPanel>

如果您想搜索 Foo,请尝试...

<ComboBox IsEditable = "True" TextSearch.TextPath = "Foo" />

默认情况下,

ComboBox
有一种自动完成功能,可以根据第一个字母查找匹配项 - 假设您的源按字母顺序排序,这会将所选项目移动到(例如)以“e”开头的部分。

如果您希望有多个以同一字母开头的条目,则捕获

KeyDown
强制打开下拉菜单可能会很有用。


15
投票

假设您的项目按字母顺序排序,只需设置

IsTextSearchEnabled="True"
即可跳转到以您在
ComboBox
中输入的字母(或多个字母)开头的项目。

这是我的

ComboBox
之一的示例,我简化了绑定,因为它显然不是这里的重要部分...

<ComboBox ItemsSource="{Binding MyObjectList}"
          DisplayMemberPath="Description"
          SelectedValuePath="Code"
          IsTextSearchEnabled="True"/>

这非常适合从列表中选择一个值,但是,您键入的搜索值不会显示在控件的 TextBox 部分中,因为我将

IsEditable
设置为 false。

如果有人想解释为什么这被否决,我将不胜感激,我不认为我提供的答案有任何问题,也不明白为什么当我只是想这样做时我应该失去声誉帮助(并提供了合理的答案!)


1
投票

我所要做的就是添加以下内容:

TextSearch.TextPath="<what ever you bound to goes here> ie:State or name "

0
投票

我知道这是一篇旧帖子,但这可能会对某人有所帮助。 如果您正在使用绑定(您应该这样做)以及 ItemSource 和 SelectedItem,那么只需添加 TextSearch.TextPath="您的绑定显示属性" 正如@mwolff 所述即可正常工作。

<ComboBox Grid.Row="2" Grid.Column="0" Height="25" VerticalContentAlignment="Center" HorizontalAlignment="Center" Width="150" ItemsSource="{Binding EquipmentTypes, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding SelectedEquipmentType,Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" 
        SelectedValuePath="Equipment_Type_ID" 
TextSearch.TextPath="Equipment_Type_Code" 
        ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ComboBox.Resources>
    <Style TargetType="Popup">
        <Setter Property="Width" Value="155"/>
    </Style>
</ComboBox.Resources>
<ComboBox.ItemTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding Equipment_Type_Code}" TextWrapping="NoWrap" />
    </DataTemplate>
</ComboBox.ItemTemplate>
© www.soinside.com 2019 - 2024. All rights reserved.