Search code examples
c#wpfxamlfocusable

How to set all Controls in wpf to unfocusable?


I have a wpf application and I want to set everything to Focusable="false". Is there an easy and elegant way? Currently I made a style for each type of Control I use like this:

<Style TargetType="Button">
<Setter Property="Focusable" Value="False"></Setter>
</Style>

Any idea for a more universan solution?


Solution

  • Why not try a two line solution ?

     foreach (var ctrl in myWindow.GetChildren())
    {
    //Add codes here :)
    }  
    

    Also make sure to add this :

      public static IEnumerable<Visual> GetChildren(this Visual parent, bool recurse = true)
     {
    if (parent != null)
    {
        int count = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < count; i++)
        {
            // Retrieve child visual at specified index value.
            var child = VisualTreeHelper.GetChild(parent, i) as Visual;
    
            if (child != null)
            {
                yield return child;
    
                if (recurse)
                {
                    foreach (var grandChild in child.GetChildren(true))
                    {
                        yield return grandChild;
                    }
                }
            }
        }
    }
    }
    

    Or even shorter, use this :

    public static IList<Control> GetControls(this DependencyObject parent)
    {            
        var result = new List<Control>();
        for (int x = 0; x < VisualTreeHelper.GetChildrenCount(parent); x++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, x);
            var instance = child as Control;
    
            if (null != instance)
                result.Add(instance);
    
            result.AddRange(child.GetControls());
        } 
        return result;
    }