获取DataTemplate控件内的控件

我有以下用于Windows 8.1的集线器应用程序的XAML代码:

                     

问题是我无法访问MapLayer和c#页面中的Grid控件。 (只有当XAML在DataTepmlate控件内时才会出现问题)。 我怎样才能获得此访问权限?

您应该使用VisualTreeHelper方法。 这只是我正在使用的一些代码。 我认为你可以根据自己的需要轻松调整它。

首先将FindElementByName方法放在代码隐藏文件的某处:

 public T FindElementByName(DependencyObject element, string sChildName) where T : FrameworkElement { T childElement = null; var nChildCount = VisualTreeHelper.GetChildrenCount(element); for (int i = 0; i < nChildCount; i++) { FrameworkElement child = VisualTreeHelper.GetChild(element, i) as FrameworkElement; if (child == null) continue; if (child is T && child.Name.Equals(sChildName)) { childElement = (T)child; break; } childElement = FindElementByName(child, sChildName); if (childElement != null) break; } return childElement; } 

现在您可以开始使用该方法了。 将事件处理程序添加到MapLayer或Map中,如下所示:

  

在你的处理程序中,你现在可以使用这样的代码访问元素(你可能需要调整它,因为我对Hubsection控件不太熟悉):

 this.UpdateLayout(); // Give your hub a name using x:Name= var item = [..] // Retrieve your hubsection here! var container = this.MyHubSection.ContainerFromItem(item); // NPE safety, deny first if (container == null) return; var datalayer = FindElementByName(container, "DataLayer"); // And again deny if we got null if (datalayer == null) return; /* Start doing your stuff here. */