I created a simple WPF UserControl
that has a Grid
as its Content
control that reacts to MouseEnter
, MouseLeave
, and MouseDown
events. Basically it is behaving like a button at this point, changing color when hovered and doing something when clicked.
I want this control to also implement tab stopping and get focus when tabbing though the controls. I tried setting IsTabStop
on the containing UserControl
, but that didn't seem to do anything.
Also, while the UserControl.Content
is a Grid
, the Grid
can also have Children
added to it, but I want that root Grid
to be what gets tab stopped.
Any ideas how I can implement this?
UserControl.xaml
<UserControl x:Class="WpfApp1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="100" Height="100" Focusable="False">
<Grid x:Name="grid" Background="Black" Focusable="True"
MouseEnter="Grid_MouseEnter"
MouseLeave="Grid_MouseLeave"
MouseDown="Grid_MouseDown"
GotFocus="Grid_GotFocus">
<TextBlock Text="UserControlButton?" Foreground="White"/>
</Grid>
</UserControl>
UserControl.cs
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
grid.FocusVisualStyle = null;
}
// hover
private void Grid_MouseEnter(object sender, MouseEventArgs e) => grid.Background = new SolidColorBrush(Colors.Red);
private void Grid_MouseLeave(object sender, MouseEventArgs e) => grid.Background = new SolidColorBrush(Colors.Black);
private void Grid_MouseDown(object sender, MouseButtonEventArgs e) => grid.Background = new SolidColorBrush(Colors.Blue);
// tabstop
private void Grid_GotFocus(object sender, RoutedEventArgs e) => grid.Background = new SolidColorBrush(Colors.Orange);
private void grid_MouseUp(object sender, MouseButtonEventArgs e)
{
}
}