我有以下用于Windows 8.1的集线器应用程序的XAML代码:
<HubSection Width="780" Margin="0,0,80,0">
<HubSection.Background>
<ImageBrush ImageSource="Assets/MediumGray.png" Stretch="UniformToFill" />
</HubSection.Background>
<DataTemplate>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<m:Map Credentials="YOUR_BING_MAPS_KEY">
<m:Map.Children>
<!-- Data Layer-->
<m:MapLayer Name="DataLayer"/>
<!--Common Infobox-->
<m:MapLayer>
<Grid x:Name="Infobox" Visibility="Collapsed" Margin="0,-115,-15,0">
<Border Width="300" Height="110" Background="Black" Opacity="0.8" BorderBrush="White" BorderThickness="2" CornerRadius="5"/>
</Grid>
</m:MapLayer>
</m:Map.Children>
</m:Map>
</Grid>
</DataTemplate>
</HubSection>
问题是我无法访问c#页面中的MapLayer
和Grid
控件。
(只有当XAML在DataTepmlate
控件内时才会出现问题)。
我怎样才能获得这种访问权限?
答案 0 :(得分:2)
您应该使用VisualTreeHelper方法。这只是我正在使用的一些代码。我认为你可以根据自己的需要轻松调整它。
首先将FindElementByName方法放在文件后面的代码中:
public T FindElementByName<T>(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<T>(child, sChildName);
if (childElement != null)
break;
}
return childElement;
}
现在您可以开始使用该方法了。将事件处理程序添加到MapLayer或Map中,如下所示:
<m:MapLayer Name="DataLayer" Loaded="DataLayerLoaded" />
在你的处理程序中,你现在可以使用这样的代码访问元素(你可能需要调整它,因为我对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<MapLayer>(container, "DataLayer");
// And again deny if we got null
if (datalayer == null)
return;
/*
Start doing your stuff here.
*/