How to programmatically access Control in WPF Grid

2020-01-28 02:15发布

Once Controls have been added to a WPF Grid, is there a way to programmatically access them by row and/or column index? Something along the lines of:

 var myControl = (object)MyGrid.GetChild(int row, int column);

... where GetChild is the method I wish I had!

标签: wpf grid row
5条回答
Animai°情兽
2楼-- · 2020-01-28 02:55

System::Windows::Controls::Grid^ myGrid = nullptr; System::Windows::Controls::UserControl^ pUserControl = nullptr;

myGrid = m_DlgOwnedObjAdmin->GrdProperties;
if (myGrid->Children->Count > 0)
{
    pUserControl = (System::Windows::Controls::UserControl^)myGrid->Children->default[0];
    if (pUserControl != nullptr)
    {
        if (bValue == true)
            pUserControl->Visibility = System::Windows::Visibility::Visible;
        else
            pUserControl->Visibility = System::Windows::Visibility::Collapsed;
    }
}
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-01-28 02:59

you could just give your grid column/row a name

<Grid x:Name="MainGridBackground" Grid.Column="0"/>

and access it programmatically by calling it and using "."

MainGridBackground.Background = canvasUCInstance.rectanglePreview.Fill;
查看更多
Root(大扎)
4楼-- · 2020-01-28 03:05

The Children property of the grid object will give you a collection of all the children of the Grid (from the Panel class).

As far as getting the coordinates in the grid, look at the static methods in the Grid class (GetRow() & GetColumn()).

Hope that sets you off in the right direction.

查看更多
家丑人穷心不美
5楼-- · 2020-01-28 03:06

This answer will help you

int rowIndex = Grid.GetRow(myButton);

RowDefinition rowDef = myGrid.RowDefinitions[rowIndex];
查看更多
放荡不羁爱自由
6楼-- · 2020-01-28 03:16

There isn't a built-in method for this, but you can easily do it by looking in the Children collection:

myGrid.Children
      .Cast<UIElement>()
      .First(e => Grid.GetRow(e) == row && Grid.GetColumn(e) == column);
查看更多
登录 后发表回答