I am writing a WPF GUI application using .NET 6.
I have a following visual structure in my main window, but please note ScrollViewer and DockPanel inside it.
<DockPanel>
<!-- .... some more components here.... -->
<ScrollViewer x:Name="scvApplications"
HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled">
<DockPanel x:Name="pnlApplications" HorizontalAlignment="Left">
</DockPanel>
</ScrollViewer>
</DockPanel>
I want to focus a button programmatically and have custom focus style, just a simple solid black border.
For custom focus style I've added following Style definition into my window XAML:
<Window.Resources>
<Style x:Key="AppButtonFocusStyle" TargetType="Control">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Rectangle StrokeThickness="2" Stroke="Black" SnapsToDevicePixels="true"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
I am creating each of those buttons programmatically, like this:
_appButtonFocusStyle = (Style)FindResource("AppButtonFocusStyle");
// ....
var appButton = new Button()
{
Name = $"btn{_nextAppButtonId++}",
Content = "some text on the button",
Background = Brushes.Transparent,
BorderBrush = Brushes.Transparent,
FocusVisualStyle = _appButtonFocusStyle,
Tag = "something"
};
appButton.Click += ApplicationButton_Click;
pnlApplications.Children.Add(appButton);
Then, at some point, I'm doing
Activate();
firstButton.Focus();
in the code, where firstButton
is a first button created. But with this, neither default, nor my custom focus border is drawn. However, when I press right arrow key, focus does move to a next button, my custom focus rectangle is correctly drawn on it. Then, when I press left arrow key, and focus moves back to the button that I've initially focused programmatically, and the custom focus rectangle is correctly removed from focused "next" button and correctly drawn on the "first" button.
From this, I make conclusion that when I've done the firstButton.Focus()
, "firstButton" actually have received the focus, but for some reason focus rectangle was not drawn. Can someone please explain and advise, why is this happening and how to fix it?