Question

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!

Was it helpful?

Solution

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

OTHER TIPS

This answer will help you

int rowIndex = Grid.GetRow(myButton);

RowDefinition rowDef = myGrid.RowDefinitions[rowIndex];

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.

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

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top