且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在WPF的网格中获取指定行和列的对象?

更新时间:2023-10-19 16:23:58

WPF网格的行和列属性实际上是附加的依赖项属性.因此,必须包括某些静态方法,以便这些属性在XAML中可用.您只需要遍历Grid的子级以确保遍历Grid中的对象,然后使用相同的方法来获取对象的列和行.

以下代码是如何执行此操作的简单示例.请记住,它是在每个项目的列和行跨度为1的前提下运行的.为了安全起见,您还需要抓住对象的列和行的跨度,然后执行进行一些数学运算,以确保对象与所需位置重叠.

The row and column properties for a WPF Grid are really attached dependency properties. So, certain static methods must be included inorder for those properties to be usable in XAML. You only need to loop through the children of the Grid to make sure you''re going through the objects in the grid, and then you use those same methods to get the column and row of the object.

The following code is a simple example of how to do this. Please keep in mind that it runs under the assumption that each item has a column and row span of 1. In order to be on the safe side, you will also to have grab the spans of the objects'' columns and rows, and do a little math to be sure an object overlaps the position you want.

foreach (UIElement item in someGrid.Children)
{
   int column = Grid.GetColumn(item);
   int row = Grid.GetRow(item);

   if (column == expectedColumn && row == expectedRow)
   {
      // Do something.
   }
}



请参阅此论坛:
social.msdn.microsoft.com/Forums/en/wpf/线程/74332b78-6bfd-4ac9-af85-dfd9bec87a29

refer to this forum:
social.msdn.microsoft.com/Forums/en/wpf/thread/74332b78-6bfd-4ac9-af85-dfd9bec87a29