如何在WPF的StackPanel中查找每个数据网格

本文关键字:数据 数据网 网格 查找 WPF StackPanel | 更新日期: 2023-09-27 18:10:53

在我的XAML中,我有以下stackpanel,可以包含元素列表,其中一些将是数据格(有些不是)

    <ScrollViewer Name="MainScrollViewer" Grid.Row="0">
        <StackPanel Name="MainStackPanel">
            // label
            // datagrid
            // label
            // button
            // datagrid
            // .....
        </StackPanel>
    </ScrollViewer>

datagrids的名称和数量是动态的(我不知道)。

在我的XAML.CS中,我需要做以下工作-对于stackpanel中的每个datagrid-打印出来

现在我知道如何打印(这不是问题),但我很难找出如何访问stackpanelFOREACH数据网格中的所有元素…

什么线索吗?

如何在WPF的StackPanel中查找每个数据网格

foreach (DataGrid dataGrid in MainStackPanel.Children.OfType<DataGrid>())
{
}

 foreach (UIElement child in MainStackPanel.Children)
        {
            DataGrid dataGrid = child as DataGrid;
            if (dataGrid != null)
            {
                //your code here
            }
        }

你可以试试这个方法。没有测试,希望它能工作:

    List <DataGrid> dataGridList = new List<DataGrid>();
    for (int i = 0; i < MainStackPanel.Children.Count; i++)
    {
        if (typeof(DataGrid) == MainStackPanel.Children[i].GetType())
        {
            dataGridList.Add((DataGrid) MainStackPanel.Children[i]);
        }
    }
    foreach(DataGrid dg in dataGridList)
    {
        // add your code
    }

请看下面的例子。由于StackPanel's Children属性包含一个UIElementCollection,您可以遍历它,寻找您需要的控件类型。

private StackPanel _stackPanelContainer = MainStackPanel; // Get a reference to the StackPanel w/ all the UI controls
// Since StackPanel contains a "List" of children, you can iterate through each UI Control inside it
//
foreach (var child in _stackPanelContainer.Children)
{
   // Check to see if the current UI Control being iterated over is a DataGrid
   //
   if (child is DataGrid)
   {
       // perform DataGrid printing here, using the child variable
   }
}