由于您正在循环使用Items
集合,这是您的ItemsSource
。为什么不把bool property
放在你自己的课堂上,并从那里得到它。
说,如果的ItemSource是List<Person>
,然后创建一个布尔属性说,在Person
类IsManager
,并与你的复选框,这样将其绑定 -
<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
}
}
我的课是从EF生成的。并且我的班级中不需要布尔值 – Raika
对此有何建议? – Raika
用另一种方法更新了答案。看看这是否有帮助。 –