1
votes

For the application I am developing, I would like to use a Hub with three WebViews in it that you can scroll across. I have tried:

  • Simply putting the WebView in the Hub Section (this does not work- a DataTemplate is needed)

  • Putting the WebView inside a DataTemplate in the HubSection (this compiles, but the WebView is not accessible to the Code Behind)

  • Using the following code to attempt to find the control visually while using the above method:

    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;
    }
    

This does not find any visual elements. How can I have a Hub with WebViews inside of it?

2

2 Answers

1
votes

Make sure you only search the VisualTree after the Page has loaded.

<Page Loaded="Page_Loaded">
    <Grid>
       <Hub x:Name="myHub">
            <HubSection x:Name="myHubSection">
                <DataTemplate>
                    <WebView x:Name="myWebView"></WebView>
                </DataTemplate>
            </HubSection>
        </Hub>
    </Grid>
</Page>

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    var hub_section = FindVisualChildByName<HubSection>(this.myHub, "myHubSection");
    var web_view = FindVisualChildByName<WebView>(hub_section, "myWebView");
}

enter image description here

-2
votes

Do it like Chubosaurus Software said in his answer. Make sure you have loaded the WebView!

But you don't have to search for the HubSection, you can simply use its name in that function like this:

WebView webview = FindChildControl<WebView>(WebViewSectionName, "MyWebView") as WebView;