Since you iterate over the Items collection, which is your ItemsSource . Why not have a bool property in your class and get it from there yourself.
Say if ItemSource List<Person> then create a bool say IsManager in Person class and bind it with checkbox like this -
<CheckBox IsChecked="{Binding IsManager}"/>
Now you can iterate over the elements to get a value like this -
foreach(Person p in grdData.ItemsSource) { bool isChecked = p.IsManager; // Tells whether checkBox is checked or not }
EDIT
If you cannot create a property, I would suggest using VisualTreeHelper methods to find the control. Use this method to search for a child (perhaps you can put it in some utility class and use it, since its common) -
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 name is set for search if (frameworkElement != null && frameworkElement.Name == childName) { // if the child name is of the request name foundChild = (T)child; break; } } else { // child element found. foundChild = (T)child; break; } } return foundChild; }
Now use the above method to get the status of your checkbox -
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 ) {
source share