Home > Software engineering >  How can I make a Grid that has tab stopping behavior?
How can I make a Grid that has tab stopping behavior?

Time:09-02

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?

CodePudding user response:

The Grid has its Focusable property set to false by default, so it will not receive focus of any kind.

Gets or sets a value that indicates whether the element can receive focus.

When deriving from UIElement directly (as opposed to from Control), consider whether you wish your element to be focusable, because by default the element will not be focusable.

If you set it to true, it will automatically participate in tabbing.

<Grid Focusable="True" KeyboardNavigation.TabNavigation="None"  Background="Yellow">

If you only want the Grid to be a tab stop, but not its children, set the TabNavigation property to None.

No keyboard navigation is allowed inside this container.

<Grid Focusable="True" KeyboardNavigation.TabNavigation="None"  Background="Yellow">

CodePudding user response:

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)
    {
        
    }
}
  • Related