Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 寻找孩子的孩子_C#_Wpf_Parent Child - Fatal编程技术网

C# 寻找孩子的孩子

C# 寻找孩子的孩子,c#,wpf,parent-child,C#,Wpf,Parent Child,我有以下代码- WebBrowser bw = new WebBrowser(); Grid gr = new Grid(); gr = ((ClosableTab)tabControl1.Items[tabControl1.SelectedIndex]).Content as Grid; Grid grc = new Grid(); grc = gr.Children[1] as Grid; bw = grc.Children[0] as WebBrowser; bw.Source = new

我有以下代码-

WebBrowser bw = new WebBrowser();
Grid gr = new Grid();
gr = ((ClosableTab)tabControl1.Items[tabControl1.SelectedIndex]).Content as Grid;
Grid grc = new Grid();
grc = gr.Children[1] as Grid;
bw = grc.Children[0] as WebBrowser;
bw.Source = new Uri(txtBoxUrl.Text);
无论我如何能满足我的要求,但所有的元素都是硬编码的。 我知道有更好的方法和一行代码。请建议使用标准代码来执行此操作

更新

<TabControl x:Name="tabControl1" FontWeight="UltraBlack" BorderThickness="1" BorderBrush="Black" Background="LightBlue" >
            <local:ClosableTab Background="LightBlue" Title="Preview" x:Name="PreviewWindow">
                <Grid>
                    <Border Name="mask" Background="Black" CornerRadius="5"/>
                    <Grid>
                        <Grid.OpacityMask>
                            <VisualBrush Visual="{Binding ElementName=mask}"/>
                        </Grid.OpacityMask>
                        <WebBrowser Name="webBrowser" Source="http://www.google.com" Margin="0" />
                    </Grid>
                </Grid>
            </local:ClosableTab>
            <local:AddableTab Background="LightBlue">
                Click '+' to add a New Tab
            </local:AddableTab>
        </TabControl>

单击“+”添加新选项卡

您可以使用helper函数按名称查找子项。试试这个

然后可以像这样调用函数:

DependencyObject parent = tabControl1.Items[tabControl1.SelectedIndex])
WebBrowser wb = UIHelper.FindChild<WebBrowser>(parent, "WebBrowser");
wb.Source = new Uri(txtBoxUrl.Text);
DependencyObject父项=tabControl1.Items[tabControl1.SelectedIndex])
WebBrowser wb=UIHelper.FindChild(父,“WebBrowser”);
wb.Source=新Uri(txtBoxUrl.Text);

@Blachshma:谢谢你的评论,但我想通过后端编码来完成。正如您所看到的,它是动态的,它取决于SelectedIndex为什么要创建一个新网格,然后为其赋值<代码>网格gr就足够了。WebBrowser等也是如此。@user2039445也许您可以发布xaml标记。这将有助于我们了解您想要了解的内容do@Blachshma:请查看更新我可以这样做,但我正在动态添加和关闭选项卡。每个选项卡都有自己的浏览器控件,具有相同的层次结构。我只是展示了层次结构,而不是硬编码的XAML。