2012-10-14 105 views
4

的DataGridTemplateColumn我有这样的XAML获取复选框的值在DataGrid中

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

我试试这个代码来获取经过国家

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

我的代码是错误的?

回答

5

由于您正在循环使用Items集合,这是您的ItemsSource。为什么不把bool property放在你自己的课堂上,并从那里得到它。

说,如果的ItemSource是List<Person>,然后创建一个布尔属性说,在PersonIsManager,并与你的复选框,这样将其绑定 -

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

现在你可以遍历所有的项目得到这样的价值 -

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

EDIT

万一你不能创建一个属性,我会建议使用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 
    } 
} 
+0

我的课是从EF生成的。并且我的班级中不需要布尔值 – Raika

+0

对此有何建议? – Raika

+1

用另一种方法更新了答案。看看这是否有帮助。 –