简体   繁体   中英

How To Control Keyboard Focus Inside a UserControl

I have a simple UserControl Which contains some TextBlock s. Also I have some of my UserControl s in a StackPanel , Normally when I press arrow keys keyboard focus moves between UserControl s and that's the behavior I DON"T WANT.

I want to handle arrow keys press inside the UserControl and stop keyboard navigation normal behavior, Just like a TextBox . How Can I Do That?

<StackPanel  >
    <dtp:DatePicker  VerticalAlignment="Top"/> <!-- When I press down arrow key on this element, keyboard navigation moves to next element-->
    <dtp:DatePicker  VerticalAlignment="Top" DisplayType="DateOnly"/>
    <dtp:DatePicker  VerticalAlignment="Top" DisplayType="TimeOnly"/>
    <dtp:DatePicker  VerticalAlignment="Top" HasSeconds="False"/>
    <dtp:DatePicker  VerticalAlignment="Top" DisplayType="DateOnly" HasSeconds="False"/>
    <dtp:DatePicker  VerticalAlignment="Top" DisplayType="TimeOnly" HasSeconds="False"/>
</StackPanel>

Normally, with controls just inside a StackPanel, simple controls don't lost focus when pressing an arrow key. You can try it with just this little test.

<StackPanel>
    <DatePicker/>
    <DatePicker/>
    <DatePicker/>
</StackPanel>

Maybe your problem is outside the dtp:DatePicker controls. Maybe you are putting the StackPanel in an ItemTemplate ?

Anyway, you can try to neutralize the arrow keys with the PreviewKeyUp event like this :

<dtp:DatePicker PreviewKeyUp="OnPreviewKeyUp"/>

private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Up || e.Key == Key.Down)
        e.Handled = true;
}

Or you can try to put a navigation constraint with Navigation mode :

<dtp:DatePicker KeyboardNavigation.DirectionalNavigation="None" 
                KeyboardNavigation.TabNavigation="None"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM