How can I prevent tabbing to a UserControl?

前端 未结 6 2210
青春惊慌失措
青春惊慌失措 2020-12-17 16:58

I have a custom Popup that overlays part of my screen. When it is open, I want to disable tabbing into the UserControl behind it. I do not want to use the IsEnabled

相关标签:
6条回答
  • 2020-12-17 17:43

    This worked for me:

    // ...
    
    var applicationWindow = Application.Current?.MainWindow;
    if (applicationWindow != null)
    {
        KeyboardNavigation.SetIsTabStop(
            element: applicationWindow, 
            isTabStop: false);
    
        KeyboardNavigation.SetTabNavigation(
            element: applicationWindow, 
            mode: false);
    }
    
    // ...
    

    Note: it is good to have a backup plan for restoring the Keyboard navigation in case if the above is needed only temporarily.

    0 讨论(0)
  • 2020-12-17 17:44

    You could write an attached property that you would set in the top element.
    That attached property would recursively set IsTabStop to false in all the child elements.

    Let me know if you need any help getting this to work.

    0 讨论(0)
  • 2020-12-17 17:48

    The solution with KeyboardNavigation.TabNavigation="None" seems to bubble up to all other parent containers in my case. This is maybe not wanted in some scenarios. So I came up with a PreviewKeyDown-Event in code behind like this:

        private void OnPreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Tab)
            {
                ((Control)sender).Focus(); 
                e.Handled = true;
            }
        }
    
    0 讨论(0)
  • 2020-12-17 17:52

    Use the KeyboardNavigation.TabNavigation Attached Property with KeyboardNavigationMode.None on your container control.

    KeyboardNavigation.TabNavigation="None"
    
    0 讨论(0)
  • 2020-12-17 17:54

    You can bind IsTabStop on the child controls to IsTabStop on the UserControl.

    That way, you only have to set it once.

    0 讨论(0)
  • 2020-12-17 17:55

    Just bind that property to the user control.

        <UserControl x:Class="PDV.UserControls.InputField"
                     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                     // etc... then:                     
                     x:Name="Root" KeyboardNavigation.TabNavigation="Local" >
    
            <Grid>
               <TextBox Name="textBox"  
                    TabIndex="{Binding Path=TabIndex, ElementName=Root}" 
                    IsTabStop="{Binding Path=IsTabStop, ElementName=Root}"  />                
            </Grid>
        </UserControl>
    
    0 讨论(0)
提交回复
热议问题