How can I trap the keyup event on the first item i

2019-05-12 00:20发布

问题:

I have a ListBox with a TextBox above it. I would like to use the arrow keys to navigate from the ListBox to the TextBox.

The intention is that if the first item in the ListBox is selected, and the user keys up, the TextBox will get focus.

I nearly have this working, but the problem is that when the user keys up, the SelectedItem is changed before the KeyUp event is raised. This means that the navigation to the TextBox happens when the user has selected the second item in the ListBox.

How can I trap the keyup event on the first item in a ListBox?

<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();
        }
    }

回答1:

Assuming you really want to to this, you can use PreviewKeyDown as follows:

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

with this code-behind:

    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;
                }
            }
        }
    }