Reputation: 878
I have the following XAML code that used on hub application for windows 8.1:
<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>
The problem is that I can't access to MapLayer
and to the Grid
controls in the c# page.
(The problem happens only whe the XAML is inside the DataTepmlate
control).
How can I get this access?
Upvotes: 2
Views: 1401
Reputation: 3362
You should use a VisualTreeHelper method. This is just some code I am using. I think you can easily adjust it to your needs.
First put the FindElementByName method somewhere into your code behind file:
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;
}
Now you can start using the method. Add an event handler to your MapLayer or to your Map like this:
<m:MapLayer Name="DataLayer" Loaded="DataLayerLoaded" />
Inside your handler you can now access the element with code like this (you might have to adjust this as I am not too familiar with the Hubsection control):
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.
*/
Upvotes: 2