VB.Net WPF ComboBox - 取消选择项目

时间:2015-10-19 13:57:55

标签: wpf vb.net combobox reset selecteditem

我在WPF程序中有一个ComboBox。它绑定到来自SQL查询的字符串列表。当我运行程序时,ComboBox开始为空(selectedIndex = -1)。从ComboBox中选择一个项目后,我所能做的就是保留该项目或选择其他项目。但是,我无法使用删除键来清除选择。有没有办法将Delete键绑定到组合框,以便清除选择(将SelectedIndex设置回-1)?

1 个答案:

答案 0 :(得分:1)

如果您使用的是绑定,可以这样做:

<ComboBox Name="cbo1" SelectedIndex="{Binding CboSelectedIndex}" >
    <ComboBox.InputBindings>
        <KeyBinding Key="Delete" Command="{Binding SetSelectedIndex}"/>
    </ComboBox.InputBindings>
</ComboBox>

命令&#34; SetSelectedIndex&#34;将设置依赖属性&#34; CboSelectedIndex&#34;为-1。

有了代码,你可能会遇到这样的事情:

<ComboBox Name="cbo1"/>

代码隐藏(在InitializeComponent()之后):

Dim command As New ActionCommand(Sub()
                                     cbo1.SelectedIndex = -1
                                 End Sub)

cbo1.InputBindings.Add(New KeyBinding(command, New KeyGesture(Key.Delete)))

不用说&#34; ActionCommand&#34;是ICommand的标准/样板实现:

Public Class ActionCommand
    Implements ICommand
    Private ReadOnly _action As Action
    Public Sub New(action As Action)
        _action = action
    End Sub
    Private Function ICommand_CanExecute(parameter As Object) As Boolean Implements ICommand.CanExecute
        Return True
    End Function
    Private Sub ICommand_Execute(parameter As Object) Implements ICommand.Execute
        _action()
    End Sub
    Public Event CanExecuteChanged As EventHandler
    Private Event ICommand_CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged
End Class