TreeView 中CheckBox级联选中问题

 1 private void Init()   

 2 {   

 3     TreeViewItem tvi_0 = new TreeViewItem(); 

 4       

 5     CheckBox cb = new CheckBox();

 6 cb.Content = "所有";

 7     cb.Checked += new RoutedEventHandler((sender, e) =>{foreach (TreeViewItem item in tvi_0.Items){((item.Header as StackPanel).Children[0] as CheckBox).IsChecked = true;}});   

 8     cb.Unchecked += new RoutedEventHandler((sender, e) =>{foreach (TreeViewItem item in tvi_0.Items){((item.Header as StackPanel).Children[0] as CheckBox).IsChecked = false;}});   

 9 

10 StackPanel sp = new StackPanel(); 

11     sp.Children.Add(cb);  

12 

13 tvi_0.Name = "0"; 

14     tvi_0.Header=sp;//关键就是在 这个 Header   

15     tvi_0.IsExpanded = true;

16 

17     treeview_1.Items.Add(tvi_0);  

18 

19     TreeViewItem tviTmp = null;   

20     StackPanel sptmp = null;   

21     CheckBox cbtmp = null;   

22     for (int i = 0; i < 10; i++)   

23     {   

24    tviTmp = new TreeViewItem();   

25    sptmp = new StackPanel();   

26    cbtmp = new CheckBox();

27 

28    tviTmp.Name = "tviTmp"+i.ToString();   

29    cbtmp.Name = "cbtmp"+i.ToString();   

30    sptmp.Name = "sptmp"+i.ToString();

31 

32    cbtmp.Content = "CheckBox" + i.ToString();   

33    sptmp.Children.Add(cbtmp);   

34    tviTmp.Header = sptmp;   

35    tvi_0.Items.Add(tviTmp);   

36     }   

37 }

你可能感兴趣的:(checkbox)