Finding the dialog a silverlight FrameworkElement lives in?
-
23-03-2021 - |
Вопрос
I have a silverlight app consisting of several dialogs each with a collection of FrameworkElement
s in it.
Is it possible to find the dialog in which a Framework element is in?
Решение
You can use the VisualTreeHelper
. The code below is what I use to find the Page
in a WPF application. You can replace Page with whatever container you need in Silverlight, maybe Popup
.
var parent = VisualTreeHelper.GetParent(this);
while (!(parent is Page))
{
parent = VisualTreeHelper.GetParent(parent);
}
Другие советы
http://forums.silverlight.net/p/55369/142519.aspx has a method to simplify the above example code and make it generic-friendly:
public static class ControlFinder
{
public static T FindParent<T>(this UIElement control) where T: UIElement
{
UIElement p = VisualTreeHelper.GetParent(control) as UIElement;
if (p != null)
{
if (p is T)
return p as T;
else
return ControlFinder.FindParent<T>(p);
}
return null;
}
}
Use it like:
var page = myElement.FindParent<Page>();
Yes it is possible. If you know the structure of your control, then you can user FrameworkElement.GetParent()
or else you can use Tree-traversal algorithms like BFS or DFS to find the your framework element.
Не связан с StackOverflow