我在WPF中有一个控件,它有一个唯一的Uid。我怎样才能通过其Uid来回溯对象?
答案 0 :(得分:12)
你几乎必须通过蛮力来做。这是您可以使用的辅助扩展方法:
private static UIElement FindUid(this DependencyObject parent, string uid)
{
var count = VisualTreeHelper.GetChildrenCount(parent);
if (count == 0) return null;
for (int i = 0; i < count; i++)
{
var el = VisualTreeHelper.GetChild(parent, i) as UIElement;
if (el == null) continue;
if (el.Uid == uid) return el;
el = el.FindUid(uid);
if (el != null) return el;
}
return null;
}
然后你可以这样称呼它:
var el = FindUid("someUid");
答案 1 :(得分:4)
public static UIElement GetByUid(DependencyObject rootElement, string uid)
{
foreach (UIElement element in LogicalTreeHelper.GetChildren(rootElement).OfType<UIElement>())
{
if (element.Uid == uid)
return element;
UIElement resultChildren = GetByUid(element, uid);
if (resultChildren != null)
return resultChildren;
}
return null;
}
答案 2 :(得分:2)
这样更好。
public static UIElement FindUid(this DependencyObject parent, string uid) {
int count = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < count; i++) {
UIElement el = VisualTreeHelper.GetChild(parent, i) as UIElement;
if (el != null) {
if (el.Uid == uid) { return el; }
el = el.FindUid(uid);
}
}
return null;
}
答案 3 :(得分:1)
我对最佳答案的一个问题是它不会查看内容中元素的内容控件(例如用户控件)。为了在这些内部搜索,我扩展了函数以查看兼容控件的Content属性。
public static UIElement FindUid(this DependencyObject parent, string uid)
{
var count = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < count; i++)
{
var el = VisualTreeHelper.GetChild(parent, i) as UIElement;
if (el == null) continue;
if (el.Uid == uid) return el;
el = el.FindUid(uid);
if (el != null) return el;
}
if (parent is ContentControl)
{
UIElement content = (parent as ContentControl).Content as UIElement;
if (content != null)
{
if (content.Uid == uid) return content;
var el = content.FindUid(uid);
if (el != null) return el;
}
}
return null;
}