Neutral Scent

App developments & Gadgets

FrameworkElementの親PhoneApplicationPageを見つける

行儀悪いですが、UserControlの中からNavigationService.Navigate()を呼びたかったのです。
.Parent()で遡っていくと途中のDataTemplateでnullが返ってきてしまうので、VisualTreeHelper.GetParent()を使います。
とりあえずFraemworkElementの拡張メソッドにしてあります。



public static class ControlUtils
{
public static PhoneApplicationPage FindParentAppPage(this FrameworkElement item)
{
var page = item as PhoneApplicationPage;
if (page != null)
return page;
var elm = item as FrameworkElement;
if (elm != null)
{
var parent = VisualTreeHelper.GetParent(elm) as FrameworkElement;
if (parent != null)
return parent.FindParentAppPage();
}

return null;
}
}

追記(2011/10/15):
これ後で気づいたんですが、NavigationService使いたければこんな回りくどい事しなくても、AppでRootFrameをstaticにするとかして参照できるようにしておけばいいんですよね。
まぁ、参考まで、ということで...。