开发者

WPF : How can I sendkeys to another control without taking focus away from the target control

I've followed this question and it works well, but it takes away focus from my sending control.

What I'm trying to do is to create an entry box that works like an auto complete text box - a text box and a popup control that contains the list of matching items. I need to be able to take keys, such as Up,Down and route them to the popup control, and take the other keys and keep them on the text box.

 switch (e.Key)
        {
            case Key.Down:
            {
                if (!popup.IsOpen)
                {
                    openPopup();
                }
                else
                {
开发者_如何学Python                    PresentationSource source = PresentationSource.FromVisual( itemList );
                    if ( source == null ) return;

                    itemList.RaiseEvent(
                        new KeyEventArgs( Keyboard.PrimaryDevice, source, 0, e.Key )
                            {RoutedEvent = Keyboard.KeyDownEvent} );

                }
                break;
            }
        }

itemList above is the control that's pop'd up and focus gets transferred as soon as I call RaiseEvent.


Well it seems it's rather easy..

 <StackPanel>
    <Controls:SearchTextBox x:Name="searchBox" SearchMode="Instant" 
                              PreviewKeyDown="onSearchBoxPreviewKeyDown"
                              KeyDown="onKeyDown" 
                              Search="onSearch" Margin="5" />
    <Popup Name="popup" >
        <ListBox x:Name="itemList" 
                 SelectionMode="Extended" 
                 KeyDown="onItemListKeyDown" 
                 PreviewKeyDown="onPreviewItemListKeyDown"
                 />
    </Popup>
</StackPanel>

In the onPreviewItemListKeyDown do the following

private void onPreviewItemListKeyDown( object sender, KeyEventArgs e )
    {
        switch (e.Key)
        {
            case Key.Down:
            case Key.Up:
            case Key.Enter:
            case Key.Escape:
            case Key.Space:
            {
                // swallow
                break;
            }
            default:
            {
                searchBox.Focus();
                return;
            }
        }
    }

For any key that you don't want to process in the popup control, simply set back the focus to your initial control. As we're doing this on the preview key event, the key down even that follows is delivered to my search box control.

This doesn't 'feel' right.. but it's working for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜