【问题标题】:How can I trap the keyup event on the first item in a ListBox?如何在 ListBox 中的第一项上捕获 keyup 事件?
【发布时间】:2011-01-13 23:45:56
【问题描述】:

我有一个 ListBox,上面有一个 TextBox。我想使用箭头键从 ListBox 导航到 TextBox。

目的是如果 ListBox 中的第一项被选中,并且用户向上键,TextBox 将获得焦点。

我几乎可以完成这项工作,但问题是当用户按下键时,SelectedItem 会在引发 KeyUp 事件之前更改。这意味着当用户选择了 ListBox 中的 second 项时,会发生到 TextBox 的导航。

如何在 ListBox 的第一项上捕获 keyup 事件?

<StackPanel>
 <TextBox Name="TextBox1"></TextBox>
 <ListBox Name="ListBox1" KeyUp="ListBox_KeyUp">
  <ListBoxItem>a</ListBoxItem>
  <ListBoxItem>b</ListBoxItem>
  <ListBoxItem>c</ListBoxItem>
 </ListBox>
</StackPanel>


    private void ListBox_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Up)
        {
            if (this.ListBox1.SelectedIndex == 0)
                this.TextBox1.Focus();
        }
    }

【问题讨论】:

  • 你有没有想过用 KeyDown 来代替?
  • @Lazarus: KeyDown 没有提出 :)
  • @Greg Sansom:那很奇怪,也许您在 ListBox 上没有看到 KeyDown,但它可能在 ListBoxItem 级别? PreviewKeyDown 或 PreviewKeyUp 似乎也提供了有趣的可能性。
  • @Lazarus:其实KeyDown为ListBoxItem引发的,但它也是在SelectionChanged之后引发的。
  • @Greg:这更有意义!!希望我能帮上忙,祝你好运。

标签: .net wpf event-handling listbox


【解决方案1】:

假设你真的想这样做,你可以使用PreviewKeyDown如下:

    <StackPanel>
        <TextBox Name="textBox1"/>
        <ListBox PreviewKeyDown="ListBox_PreviewKeyDown">
            <ListBoxItem Content="Item1" />
            <ListBoxItem Content="Item2"/>
            <ListBoxItem Content="Item3"/>
        </ListBox>
    </StackPanel>

使用此代码隐藏:

    private void ListBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (sender is ListBox)
        {
            var listBox = sender as ListBox;
            if (listBox.Items.Count > 0)
            {
                if (e.Key == Key.Up && listBox.Items.Count > 0 && listBox.SelectedIndex == 0)
                {
                    textBox1.Focus();
                    e.Handled = true;
                }
            }
        }
    }

【讨论】:

  • 您是否尝试运行该程序?这样做会告诉你它没有这个问题。通过使用 Preview,我们处理 before ListBox 的事件。
猜你喜欢
  • 1970-01-01
  • 2013-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
相关资源
最近更新 更多