我有一个 wpf 应用程序,我想将所有内容设置为 Focusable="false"。有没有简单优雅的方法?目前我为我使用的每种类型的控件制作了一个样式,如下所示:
<Style TargetType="Button">
<Setter Property="Focusable" Value="False"></Setter>
</Style>
对更通用的解决方案有任何想法吗?
为什么不尝试两行解决方案?
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;
}