C# 从DataGrid的DataGridTemplateColumn获取复选框值

C# 从DataGrid的DataGridTemplateColumn获取复选框值,c#,wpf,C#,Wpf,我有这个XAML <DataGrid Name="grdData" ... > <DataGrid.Columns> <DataGridTemplateColumn Header="Something"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox Name="

我有这个XAML

<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
    }
}
for(int i=0;i

我的代码错了?

因为您正在对
项目
集合进行循环,该集合是您的
项目资源
。为什么不在类本身中使用
bool属性
,并从类本身获取它呢

假设ItemSource是
List
,然后在类
Person
中创建一个bool属性,比如
IsManager
,并用如下复选框绑定它-

<CheckBox IsChecked="{Binding IsManager}"/>
foreach(Person p in grdData.ItemsSource)
{
   bool isChecked = p.IsManager; // Tells whether checkBox is checked or not
}
编辑

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

public static T FindChild(DependencyObject父对象,字符串childName)
其中T:DependencyObject
{
//确认父项有效。
if(parent==null)返回null;
T foundChild=null;
int childrenCount=visualtreeheloper.GetChildrenCount(父级);
for(int i=0;i
现在使用上述方法获取复选框的状态-

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
   }
}
for(int i=0;i
我的类是从EF生成的。在我的课堂上不需要布尔运算,用另一种方法更新了答案。查看这是否有帮助。当我在不同的选项卡项上使用不同的datagrid时,此方法不起作用。当我在第二个选项卡上使用另一个datagrid时,此方法不起作用。
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
   }
}