我正在尝试从DataTemplate获取SelectedRadioButton。
Wpf Inspector展示了Visual Tree:
并在代码中:
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。
答案 0 :(得分:7)
我用来遍历Visual Tree的代码没有使用ApplyTemplate()
方法在树中FrameworkElement
,因此无法找到cildren。在我的情况下,以下代码有效:
/// <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;
}
感谢“dev hedgehog”的评论指出(我错过了) 我不会在生产代码中使用这种方法,必须通过像“HighCore”评论的数据绑定来完成。