从DataGrid的DataGridTemplateColumn获取Checkbox值

时间:2012-10-14 07:55:28

标签: c# wpf

我有这个XAML

<DataGrid Name="grdData" ... >
   <DataGrid.Columns>
      <DataGridTemplateColumn Header="Something">
         <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
               <CheckBox Name="chb" />
            </DataTemplate>
         </DataGridTemplateColumn.CellTemplate>
       </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

我尝试使用此代码获取Checked State

for( int i = 0 ; i < grdData.Items.Count ; i++ )
{
    DataGridRow row = ( DataGridRow )grdData.ItemContainerGenerator.ContainerFromIndex( i );
    var cellContent = grdData.Columns[ 1 ].GetCellContent( row ) as CheckBox;
    if( cellContent != null && cellContent.IsChecked == true )
    {
       //some code
    }
}

我的代码错了?

1 个答案:

答案 0 :(得分:5)

由于您正在循环Items集合,即ItemsSource。为什么不在课堂上拥有bool property并从那里获得它。

假设ItemSource是List<Person>,然后在类IsManager中创建一个bool属性说Person并将其与你的复选框绑定 -

<CheckBox IsChecked="{Binding IsManager}"/>

现在你可以遍历Items以获得这样的值 -

foreach(Person p in grdData.ItemsSource)
{
   bool isChecked = p.IsManager; // Tells whether checkBox is checked or not
}

修改

如果您无法创建属性,我建议使用VisualTreeHelper方法来查找控件。使用此方法查找子项(也许您可以将它放在某个实用程序类中并使用它,因为它是通用的) -

public static T FindChild<T>(DependencyObject parent, string childName)
           where T : DependencyObject
{
   // Confirm parent is valid.  
   if (parent == null) return null;

   T foundChild = null;

   int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
   for (int i = 0; i < childrenCount; i++)
   {
      var child = VisualTreeHelper.GetChild(parent, i);
      // If the child is not of the request child type child 
      T childType = child as T;
      if (childType == null)
      {
          // recursively drill down the tree 
          foundChild = FindChild<T>(child, childName);

          // If the child is found, break so we do not overwrite the found child.  
          if (foundChild != null) break;
      }
      else if (!string.IsNullOrEmpty(childName))
      {
          var frameworkElement = child as FrameworkElement;
          // If the child's name is set for search 
          if (frameworkElement != null && frameworkElement.Name == childName)
          {
             // if the child's name is of the request name 
             foundChild = (T)child;
             break;
          }
      }
      else
      {
          // child element found. 
          foundChild = (T)child;
          break;
       }
   }
   return foundChild;
}

现在使用上述方法获取复选框的状态 -

for (int i = 0; i < grd.Items.Count; i++)
{
   DataGridRow row = (DataGridRow)grd.ItemContainerGenerator.ContainerFromIndex(i);
   CheckBox checkBox = FindChild<CheckBox>(row, "chb");
   if( checkBox != null && checkBox.IsChecked == true )
   {
       //some code
   }
}