我有一个wpf应用程序,我想将所有内容设置为Focusable =“false”。 有一种简单而优雅的方式吗?目前我为每种类型的Control使用了这样的样式:
<Style TargetType="Button">
<Setter Property="Focusable" Value="False"></Setter>
</Style>
对更广泛的解决方案有任何想法吗?
答案 0 :(得分:1)
为什么不尝试双线解决方案?
foreach (var ctrl in myWindow.GetChildren())
{
//Add codes here :)
}
另外请务必添加:
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;
}
}
}
}
}
}
甚至更短,请使用:
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;
}