gpt4 book ai didi

wpf - 在可视化树中查找控件

转载 作者:行者123 更新时间:2023-12-04 23:53:04 25 4
gpt4 key购买 nike

我正在尝试从 DataTemplate 获取我的 SelectedRadioButton。

Wpf Inspector 显示了可视化树:

enter image description here

在代码中:

    void menu_StatusGeneratorChanged(object sender, EventArgs e)
{
var status = Menu.Items.ItemContainerGenerator.Status;
if (status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
{
var item = Menu.Items.ItemContainerGenerator.ContainerFromIndex(0);
// item is a ContentPresenter
var control = Tools.FindChild<SelectedRadioButton>(item);
control = Tools.FindAncestor<SelectedRadioButton>(item);
}
}
item是一个 ContentPresenter,看 Wpf 检查器的图像,我相信从那里我必须能够到达 SelectedRadioButton。变量 control始终为空。
我在这里想念什么?我用这些 visualtreehelpers .

最佳答案

我用来遍历可视树的代码没有使用 ApplyTemplate() FrameworkElement 的方法在树上,因此找不到 child 。在我的情况下,以下代码有效:

    /// <summary>
/// Looks for a child control within a parent by name
/// </summary>
public static DependencyObject FindChild(DependencyObject parent, string name)
{
// confirm parent and name are valid.
if (parent == null || string.IsNullOrEmpty(name)) return null;

if (parent is FrameworkElement && (parent as FrameworkElement).Name == name) return parent;

DependencyObject result = null;

if (parent is FrameworkElement) (parent as FrameworkElement).ApplyTemplate();

int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
result = FindChild(child, name);
if (result != null) break;
}

return result;
}

/// <summary>
/// Looks for a child control within a parent by type
/// </summary>
public static T FindChild<T>(DependencyObject parent)
where T : DependencyObject
{
// confirm parent is valid.
if (parent == null) return null;
if (parent is T) return parent as T;

DependencyObject foundChild = null;

if (parent is FrameworkElement) (parent as FrameworkElement).ApplyTemplate();

int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
foundChild = FindChild<T>(child);
if (foundChild != null) break;
}

return foundChild as T;
}

感谢“开发刺猬”的评论指出了这一点(我错过了)。
我不会在生产代码中使用这种方法,它必须通过像“HighCore”注释的数据绑定(bind)来完成。

关于wpf - 在可视化树中查找控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19523139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com