Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deactivate FocusVisualStyle globally

Tags:

c#

styles

wpf

I want to globally deactivate the focus rectangles in my WPF application. For single controls that can be done via

<Style TargetType="Button">
    <Setter Property="FocusVisualStyle" Value="{x:Null}" />
</Style>

but how to apply it to all controls in my application. When applying to FrameworkElement nothing happens. What I need would be something like "apply to class x and all derived classes".

Thanks in advance,

Stefan

like image 857
grayscales Avatar asked Jun 28 '09 20:06

grayscales


4 Answers

Looks like there's no magic bullet for this:

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/141c8bfa-f152-4f8a-aca0-3c3b5440d183

like image 94
Andy Avatar answered Nov 03 '22 03:11

Andy


According to http://msdn.microsoft.com/en-us/library/bb613567.aspx, you should be able to set global focus style like this:

<Style x:Key="{x:Static SystemParameters.FocusVisualStyleKey}">
  <Setter Property="Control.Template">
    <Setter.Value>
      <ControlTemplate>
        <Rectangle StrokeThickness="1"
          Stroke="Black"
          StrokeDashArray="1 2"
          SnapsToDevicePixels="true"/>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style> 

I haven't tested it, but I guess that when you empty the controltemplate, this would effectively disable the focus rectangle for the whole app (provided you include this style in app.xaml).

like image 43
Tomáš Kafka Avatar answered Nov 03 '22 02:11

Tomáš Kafka


I stumbled upon this as well and came up with this (indeed not very nice but effective) solution:

public class FocusVisualStyleRemover
{
  static FocusVisualStyleRemover()
  {
    EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.GotFocusEvent, new RoutedEventHandler(RemoveFocusVisualStyle), true);
  }

  public static void Init()
  {
    // intentially empty
  }

  private static void RemoveFocusVisualStyle(object sender, RoutedEventArgs e)
  {
    (sender as FrameworkElement).FocusVisualStyle = null;
  }
}

In my MainWindow's constructor I then just call FocusVisualStyleRemover.Init();

like image 2
Tromse Avatar answered Nov 03 '22 02:11

Tromse


I know it sounds tedious, but you'll probably have to do the same thing for all the other control types, individually. Making a list of them and doing a couple simple Find/Replace operations should get you what you need, though.

like image 1
Joel B Fant Avatar answered Nov 03 '22 02:11

Joel B Fant