如何通过行和列索引以编程方式访问 WPF Grid 中的控件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1511722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to programmatically access Control in WPF Grid by row and column index?
提问by Mathias
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:
将控件添加到 WPF 网格后,是否可以通过行和/或列索引以编程方式访问它们?类似的东西:
var myControl = (object)MyGrid.GetChild(int row, int column);
... where GetChild
is the method I wish I had!
......GetChild
我希望我拥有的方法在哪里!
回答by itowlson
There isn't a built-in method for this, but you can easily do it by looking in the Children collection:
没有为此提供内置方法,但您可以通过查看 Children 集合轻松实现:
myGrid.Children
.Cast<UIElement>()
.First(e => Grid.GetRow(e) == row && Grid.GetColumn(e) == column);
回答by Carlo
This answerwill help you
这个答案会帮助你
int rowIndex = Grid.GetRow(myButton);
RowDefinition rowDef = myGrid.RowDefinitions[rowIndex];
回答by Eric Olsson
The Children property of the grid object will give you a collection of all the children of the Grid (from the Panel class).
网格对象的 Children 属性将为您提供 Grid 的所有子项的集合(来自 Panel 类)。
As far as getting the coordinates in the grid, look at the static methods in the Grid class (GetRow() & GetColumn()).
至于获取网格中的坐标,请查看Grid类中的静态方法(GetRow() & GetColumn())。
Hope that sets you off in the right direction.
希望这能让你朝着正确的方向前进。
回答by Sabi
System::Windows::Controls::Grid^ myGrid = nullptr; System::Windows::Controls::UserControl^ pUserControl = nullptr;
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;
}
}
回答by CLUTCHER
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;