简体   繁体   中英

WPF Toolkit ColorPicker remove focus

I'm using the ColorPicker control from the Extended WPF Toolkit with some restrictions as I want the user to only have the ColorCanvas enabled.

<xctk:ColorPicker Focusable="False" ColorMode="ColorCanvas" 
    ShowAdvancedButton="False" ShowDropDownButton="False" 
    ShowAvailableColors="False" SelectedColor="{Binding CustomAccentColor}" 
    ShowRecentColors="False" ShowStandardColors="False" />

When clicking the ToggleButton the canvas is shown and the user can pick the color he wants to. However, when clicking outside the canvas closes as expected.

Problem now is, that when pressing space-bar, the canvas is opened again. In the application it is important that nothing other than the containing Window can have focus so the space-bar pressing can be routed to a specific command.

I've already tried to set Focusable="False" , bind to the LostFocus -event and set the focus on the window in code-behind but nothing worked. The event-callback was never hit. I've also tried the SelectedColorChanged -event but this was also not working.

How I can force the focus away from the ColorPicker back to my Window ?

You will probably find that the LostFocus even is being handled on a lower control that actually has focus, thus you are not seeing it. What you can do is hook into the PreviewKeyDown event and add the following inside a check for whatever key you want to suppress:

   private void ColorPicker_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Space)
        {
            e.Handled = true;
            ColorPicker1.IsOpen = true;
        }
    }

This will override the behaviour handled in ColorPicker control by preventing it from receiving the KeyDown event. You can also move focus using something like:

    private void ColorPicker_GotFocus(object sender, RoutedEventArgs e)
    {
        ColorPicker1.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
    }

This will ensure that mouse clicks move focus back to the previous focus control. It doesn't prevent and endless loop though so make sure it doesn't focus back to itself!

Finally, you may also wish to set IsTabStop and IsKeyboardFocus to false to prevent tabbing into the color picker if you do not wish it to have focus or be tabbed into.

Note: I am using a named control here but you should be able to get the control in question through the sender.

This works for me:

private void Selected_Color_Changed(object sender, RoutedPropertyChangedEventArgs<Color?> e)
{
    YourRichTextControlElement.Focus();

    Xceed.Wpf.Toolkit.ColorPicker colorPicker = sender as Xceed.Wpf.Toolkit.ColorPicker;

    colorPicker.IsOpen = false;
 }

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