Search code examples
c#windows-store-appswinrt-xamlwindows-8.1

Access control inside hub control windows 8.1


I have this code:

<HubSection x:Name="MyHub">
    <DataTemplate>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"></RowDefinition>
                <RowDefinition Height="200"></RowDefinition>
            </Grid.RowDefinitions>
            <Image x:Name="MYImage" Source="{Binding image}" Height="50" Width="60" VerticalAlignment="Center"/>
             <StackPanel Orientation="Vertical">
                <TextBlock TextWrapping="Wrap" Width="200" VerticalAlignment="Center" HorizontalAlignment="Left" Text="{Binding name}"/>
                <Button Content="Click me">
            </StackPanel>
        </Grid>
    </DataTemplate>
</HubSection>

But I do not know how to access the text-block, I want to change the foreground color of the text-block in code behind.


Solution

  • XAML:

    <Hub x:Name="myHub">
            <HubSection x:Name="myHubSection">
                <DataTemplate>
                    <TextBlock x:Name="textbox1" Text="text" Width="300" Height="100">
                    </TextBlock>
                </DataTemplate>
            </HubSection>
        </Hub>
    

    Code behind:

     private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            var hub_section = FindVisualChildByName<HubSection>(this.myHub, "myHubSection");
            var text_box = FindVisualChildByName<WebView>(hub_section, "textbox1");
        }
    
        public static T FindVisualChildByName<T>(DependencyObject parent, string name)where T : DependencyObject
    
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                string controlName = child.GetValue(Control.NameProperty) as string;
                if (controlName == name)
                {
                    return child as T;
                }
                else
                {
                    T result = FindVisualChildByName<T>(child, name);
                    if (result != null)
                        return result;
                }
            }
            return null;
        }
    

    More detailed information you could refer to How to access a Control inside the data template in C# Metro UI in the code behind