如何将wpf中的所有控件设置为不可聚焦?
How to set all Controls in wpf to unfocusable?
我有一个 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;
}
我有一个 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;
}