简体   繁体   English

如何将WPF中的所有控件设置为无法聚焦?

[英]How to set all Controls in wpf to unfocusable?

I have a wpf application and I want to set everything to Focusable="false". 我有一个wpf应用程序,我想将所有内容都设置为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? 有更广泛的解决方案的想法吗?

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM