如何通过行列索引在WPF网格中以编程方式访问控件?

47

一旦将控件添加到WPF网格中,是否有一种可以通过行和/或列索引以编程方式访问它们的方法?例如:

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

...其中GetChild是我希望拥有的方法!

5个回答

76

没有内置的方法可以做到这一点,但是您可以通过查看Children集合来轻松实现:

myGrid.Children
      .Cast<UIElement>()
      .First(e => Grid.GetRow(e) == row && Grid.GetColumn(e) == column);

7
尽管如此,由于技术上可以在一个单元格中拥有多个元素,因为附加的属性没有检查它,所以可能值得返回完整的集合。 - Reed Copsey
谢谢。这是我迄今为止一直遵循的方法,通过迭代Children中的每个子项,直到找到一个与匹配行和列的控件,但我希望有更直接的方法。 - Mathias
3
谢谢,里德,好主意 -- 可以通过使用 Where 而不是 First 轻松实现这一点。 - itowlson
工作正常。谢谢。您可以进行强制类型转换并使用。例如:((Label)myGrid.Children[0]).Text="test"; - Ali Rasouli

12

这个答案将会帮助到您。

int rowIndex = Grid.GetRow(myButton);

RowDefinition rowDef = myGrid.RowDefinitions[rowIndex];

谢谢,但它无法完成任务,因为我没有对myButton的引用! - Mathias
这正是我正在寻找的。我已经有了对象的引用,我只需要弄清它在哪一行和列。谢谢,Carlo。 - esteuart

1

Grid对象的Children属性将为您提供Grid(来自Panel类)的所有子项的集合。

至于在网格中获取坐标,请查看Grid类中的静态方法(GetRow()和GetColumn())。

希望这能让您朝着正确的方向前进。


0

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

-1

你可以给你的网格列/行起一个名字

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

并通过调用它并使用“.”来编程访问它

MainGridBackground.Background = canvasUCInstance.rectanglePreview.Fill;

这似乎并没有回答关于在网格中获取子控件访问权限的问题。 - LarsTech
@LarsTech 它回答了如何通过编程访问网格,这就是所问的。网格的任何控件都可以通过编程调用网格的名称来访问。 - CLUTCHER

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接