jeudi 13 août 2015

Hierarchical Data Template CheckBox Checked Event for Three Levels

When I had two level of hiearchical data template, I handle with the checked event with this piece of code:

private void treeview_checked(object sender, RoutedEventArgs e)
    {
        DependencyObject dependencyObject = e.OriginalSource as CheckBox;
        while (dependencyObject != null)
        {
            dependencyObject = VisualTreeHelper.GetParent(dependencyObject);
            if (dependencyObject is TreeViewItem)
              foreach (object item in (dependencyObject as TreeViewItem).Items)
                {
                    (dependencyObject as TreeViewItem).ApplyTemplate();
                    TreeViewItem secondlevel = (dependencyObject as TreeViewItem).ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                    UIElement element = GetChildControl(secondlevel, "checkBox");
                    if (element != null)
                    {
                        CheckBox chk = (CheckBox)element;
                        chk.IsChecked = true;
                    }
                }

        }

    }

private UIElement GetChildControl(DependencyObject parentObject,string childName)
{
UIElement element=null;
if(parentObject!=null)
{
int totalChild=VisualTreeHelper.GetChildCount(parentObject);
for(int i=0; i<totalChild; i++)
{
 DependencyObject childObject=VisualTreeHelper.GetChild(parentObject,i);
 if(childObject is FrameworkElement && ((FrameworkElement)childObject).Name==childName)
    { element=childObject as UIElement; break; }
    element=GetChildControl(childObject,childName);
    if(element!=null)break;
}
}
return element;
}

When I ticked a first level checkbox, it was ticking the second level checkboxes. Now I have three levels, when I tick a first level checkbox, it does the right thing, but if I tick a second level checkbox, it ticks all the second level boxes and third level boxes under the same first level checkbox. I want tick only the second level checkbox and corresponding third level checkboxes.

First level checkboxes and second level boxes exist in HierarchicalDataTemplate, third level checkboxes exist in DataTemplate.




Aucun commentaire:

Enregistrer un commentaire