2016-07-04 34 views
0

我想CheckBoxColumn的DataGrid中值WPF遍历在WPF数据网格checkboxcolumn检查或不

我试试这个代码

foreach (spShowTotal_Result item in dgShowStudent.ItemsSource) 
     { 

      bool? check = ((CheckBox)dgShowStudent.Columns[0].GetCellContent(item)).IsChecked; 

     } 

但这种例外出现

无法转换'System.Windows.Controls.ContentPresenter'类型的对象以键入'System.Windows.Controls.CheckBox'。

+0

您在MVVM? – Gopichandar

+0

不在mvvm中,只是wpf –

+0

您是否试过[this](http://stackoverflow.com/a/6100061/2819451) – Gopichandar

回答

1

看起来像评论中提供的解决方法不适合你。让我以不同的方式解决这个问题。

考虑DataGrid作为

<DataGrid x:Name="datagridexec"> 
    <DataGridTemplateColumn Header="DUT"> 
     <DataGridTemplateColumn.CellTemplate>                 
       <DataTemplate> 
        <CheckBox x:Name="checkboxinstance"/> 
       </DataTemplate> 
     </DataGridTemplateColumn.CellTemplate> 
    </DataGridTemplateColumn> 
</DataGrid> 

,并在您xaml.cs,您可以访问像下面

List<CheckBox> checkBoxlist = new List<CheckBox>(); 

    // Find all elements 
    FindChildGroup<CheckBox>(datagridexec, "checkboxinstance", ref checkBoxlist); 

    foreach (CheckBox c in checkBoxlist) 
    { 
     if (c.IsChecked) 
     { 
      //do whatever you want 
     }  
    } 

你需要下面的类通过树进行迭代。

public static void FindChildGroup<T>(DependencyObject parent, string childName, ref List<T> list) where T : DependencyObject 
    { 
     // Checks should be made, but preferably one time before calling. 
     // And here it is assumed that the programmer has taken into 
     // account all of these conditions and checks are not needed. 
     //if ((parent == null) || (childName == null) || (<Type T is not inheritable from FrameworkElement>)) 
     //{ 
     // return; 
     //} 

     int childrenCount = VisualTreeHelper.GetChildrenCount(parent); 

     for (int i = 0; i < childrenCount; i++) 
     { 
      // Get the child 
      var child = VisualTreeHelper.GetChild(parent, i); 

      // Compare on conformity the type 
      T child_Test = child as T; 

      // Not compare - go next 
      if (child_Test == null) 
      { 
       // Go the deep 
       FindChildGroup<T>(child, childName, ref list); 
      } 
      else 
      { 
       // If match, then check the name of the item 
       FrameworkElement child_Element = child_Test as FrameworkElement; 

       if (child_Element.Name == childName) 
       { 
        // Found 
        list.Add(child_Test); 
       } 

       // We are looking for further, perhaps there are 
       // children with the same name 
       FindChildGroup<T>(child, childName, ref list); 
      } 
     } 

     return; 
    } 

参考:How to access datagrid template column textbox text WPF C#

+1

非常thxxxxxx :) –

+0

非常光滑..很好.. + 1 – BENN1TH