lundi 5 juin 2017

C# - FrameworkElement.FindName returns null

I spent the past one hour trying to figure this out, I have a checkbox inside DataGrid as follows <DataGridTemplateColumn> <DataGridTemplateColumn.Header> <CheckBox Name="chkall" Content="Select All" Checked="chkall_Checked" Unchecked="chkall_Unchecked"/> </DataGridTemplateColumn.Header> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox Tag="{Binding Path=id}" x:Name="chksingle" Checked="chksingle_Checked" Unchecked="chksingle_Unchecked"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> As you can see i am trying to check and uncheck the checkboxes inside DataGrid rows when the Checkbox in the header is checked or unchecked. you can see my code below where i am trying to retrieve the checkbox and mark it as checked.

 private void chkall_Checked(object sender, RoutedEventArgs e)
    {
        foreach (var r in userDG.Items)
        {

            DataGridRow row =(DataGridRow)userDG.ItemContainerGenerator.ContainerFromItem(r);
            FrameworkElement FW_element = userDG.Columns[0].GetCellContent(row);
            FW_element.ApplyTemplate();
            var checkbox = FW_element.FindName("chksingle") as CheckBox;
            checkbox.IsChecked = false;

        }
    }

I have already tried RegisterName() method and i tried VisualTreeHelper but nothing works.

This line always returns null. var checkbox = FW_element.FindName("chksingle") as CheckBox; and here is a WPF visualizer for my FrameworkElement where i can clearly see the checkbox i am trying to find. WPF visualizer of FrameworkElement

Please tell me what am i doing wrong? Thank you.




Aucun commentaire:

Enregistrer un commentaire