I'm writing app in Windows Phone 8.1 and I want to get access to controls from Code-Behind.
Normally everything works great but when I use hub I don't have access to fields from Code-Behind.
<Hub x:Name="RHub">
<HubSection>
<DataTemplate>
<Grid>
<TextBox x:Name="Test5"/>
</Grid>
</DataTemplate>
</HubSection>
<HubSection>
<DataTemplate>
<Grid>
</Grid>
</DataTemplate>
</HubSection>
</Hub>
And now in Code-Behind file is no such field like Test5, only RHub.
This is because the control is inside a DataTemplate. One easy way to get around this limitation is to hook into the Element Loaded-event. Here's the XAML:
<HubSection Header="Trailers">
<DataTemplate>
<ListView x:Name="MovieTrailers" Loaded="MovieTrailers_Loaded">
</ListView>
</DataTemplate>
</HubSection>
And the code-behind:
private void MovieTrailers_Loaded(object sender, RoutedEventArgs e)
{
var listView = (ListView)sender;
listView.ItemsSource = trailers;
}
if you want to search any element in the list view you can use a method like:
public static DependencyObject FindChildControl<T>(DependencyObject control, string ctrlName)
{
int childNumber = VisualTreeHelper.GetChildrenCount(control);
for (int i = 0; i < childNumber; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(control, i);
FrameworkElement fe = child as FrameworkElement;
// Not a framework element or is null
if (fe == null) return null;
if (child is T && fe.Name == ctrlName)
{
// Found the control so return
Debug.WriteLine("Achou");
return child;
}
else
{
// Not found it - search children
DependencyObject nextLevel = FindChildControl<T>(child, ctrlName);
if (nextLevel != null)
return nextLevel;
}
}
return null;
}
and search:
private void findRectangle(ListView listView)
{
Rectangle ret = this.FindChildControl<Rectangle>(listView, "ret1") as Rectangle;
if(ret != null)
{
ret.Fill = new SolidColorBrush(this.color);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.