How to programmatically access Control in WPF Grid

2020-01-28 02:52发布

问题:

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!

回答1:

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


回答2:

This answer will help you

int rowIndex = Grid.GetRow(myButton);

RowDefinition rowDef = myGrid.RowDefinitions[rowIndex];


回答3:

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.



回答4:

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


回答5:

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;


标签: wpf grid row