VB.Net WPF 组合框 - 取消选择项目
VB.Net WPF ComboBox - Unselect Item
我在 WPF 程序中有一个 ComboBox。它绑定到来自 SQL 查询的字符串列表。当我 运行 程序时,组合框开始时为空白 (selectedIndex = -1)。从 ComboBox 中选择一个项目后,我所能做的就是保留该项目或 select 一个不同的项目。但是,我无法使用删除键来清除 selection。有没有办法将 Delete 键绑定到组合框,以便它清除 selection(将 SelectedIndex 设置回 -1)?
如果您正在使用绑定,您可以这样做:
<ComboBox Name="cbo1" SelectedIndex="{Binding CboSelectedIndex}" >
<ComboBox.InputBindings>
<KeyBinding Key="Delete" Command="{Binding SetSelectedIndex}"/>
</ComboBox.InputBindings>
</ComboBox>
并且命令 "SetSelectedIndex" 会将依赖项 属性 "CboSelectedIndex" 设置为 -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)))
不用说 "ActionCommand" 是 ICommand 的 standard/boiler-plate 实现:
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
我在 WPF 程序中有一个 ComboBox。它绑定到来自 SQL 查询的字符串列表。当我 运行 程序时,组合框开始时为空白 (selectedIndex = -1)。从 ComboBox 中选择一个项目后,我所能做的就是保留该项目或 select 一个不同的项目。但是,我无法使用删除键来清除 selection。有没有办法将 Delete 键绑定到组合框,以便它清除 selection(将 SelectedIndex 设置回 -1)?
如果您正在使用绑定,您可以这样做:
<ComboBox Name="cbo1" SelectedIndex="{Binding CboSelectedIndex}" >
<ComboBox.InputBindings>
<KeyBinding Key="Delete" Command="{Binding SetSelectedIndex}"/>
</ComboBox.InputBindings>
</ComboBox>
并且命令 "SetSelectedIndex" 会将依赖项 属性 "CboSelectedIndex" 设置为 -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)))
不用说 "ActionCommand" 是 ICommand 的 standard/boiler-plate 实现:
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