【问题标题】:VB.Net WPF ComboBox - Unselect ItemVB.Net WPF ComboBox - 取消选择项目
【发布时间】:2016-01-17 22:00:22
【问题描述】:

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

【问题讨论】:

  • 用户应该在ComboBox 控件中键入一些内容以轻松找到项目,而不是删除/添加项目。您必须自己实现此功能(例如,通过按钮“删除”+yourComboBox.Items.RemoveAt(itemIndex))。
  • @varocarbas 我不想从组合框中删除项目。只是为了清除选择。在我的应用程序中,有时我不需要选择任何项目。
  • 如果用户删除选择,它应该保持空白。你也可以做yourComboBox.SelectedIndex = -1(至少在Winforms中,我认为在WPF中是一样的)。或者,您可以添加一个起始空白项并将其用于该目的。

标签: wpf vb.net combobox reset selecteditem


【解决方案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 的标准/样板实现:

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

【讨论】:

  • 谢谢,我会实现的。现在我所做的是为鼠标右键单击事件创建了一个处理程序,但它对用户来说不是很直观。这样会好很多。
猜你喜欢
  • 2016-11-26
  • 1970-01-01
  • 1970-01-01
  • 2014-07-02
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多