gpt4 book ai didi

c# - 如何在可视化树中查找元素? wp7

转载 作者:行者123 更新时间:2023-11-30 16:28:33 25 4
gpt4 key购买 nike

我如何找到包含在 App.xaml 中的元素,网格名称为“audioPanel”?我试过:

Grid found = this.FindChild<Grid>(^*I can't find anything suitable*^, "audioPanel");

How can I find WPF controls by name or type?

UPD:App.xaml http://pastebin.com/KfWbjMV8

最佳答案

更新:您需要结合我的回答和 H.B. 的回答。使用下面的 FindChild 版本,并将对 FindChild 的调用更改为如下所示

var grid = FindChild<Grid>(Application.Current.RootVisual, "audioPanel");

由于您正在设计电话应用程序框架的样式,因此 H.B. 评论中的“应用它的控件”很可能是 RootVisual(我不确定这可能有异常(exception))。

此外,我假设您在 pastebin 中的 App.xaml 的“...”部分在某处有一个 ContentPresenter,否则我认为您的风格不会奏效。

结束更新

如果您在链接到 ( WPF ways to find controls) 的问题中使用已接受的答案,并且您的“audioPanel”网格嵌套在另一个网格内,那么您仍然找不到它 - 该代码中存在错误.这是一个更新版本,即使控件是嵌套的也可以使用:

    public static T FindChild<T>(DependencyObject parent, string childName)
where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null)
{
return null;
}

T foundChild = null;

int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
var childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);

// If the child is found, break so we do not overwrite the found child.
if (foundChild != null)
{
break;
}
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Name == childName)
{
// if the child's name is of the request name
foundChild = (T) child;
break;
}

// Need this in case the element we want is nested
// in another element of the same type
foundChild = FindChild<T>(child, childName);
}
else
{
// child element found.
foundChild = (T) child;
break;
}
}

return foundChild;
}
}

关于c# - 如何在可视化树中查找元素? wp7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7034522/

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