TreeViewItem的Header是一个CheckBox,如何由CheckBox找到其所在的TreeViewItem
TreeViewItem的Header是一个CheckBox,如何由CheckBox找到其所在的TreeViewItem。代码如下:
private void setHeader()
{
......
TreeViewItem的Header是一个CheckBox,如何由CheckBox找到其所在的TreeViewItem
TreeView pTV = new TreeView();
TreeViewItem pTVItem = new TreeViewItem();
pTV.Items.Add(pTVItem);
CheckBox pCheckB = new CheckBox();
pTVItem.Header = pCheckB; //将CheckBox加入到TreeViewItem
pCheckB.Checked += new RoutedEventHandler(CheckBox_Checked);
......
}
//当CheckBox的节点被选中时
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
CheckBox pCB = sender as CheckBox;
DependencyObject parent = VisualTreeHelper.GetParent(pCB);//获取依赖的父级对象
TreeViewItem parentTreeViewItem = parent as TreeViewItem;//此处出错!
....
}
[解决办法]
注册TreeView 的SelectedItemChanged时间,在SelectedItemChanged事件里面,
TreeViewItem tvi = sender as TreeViewItem;
tvi 就是你选中的TreeViewItem ,
CheckBox cb = tvi.Header as CheckBox;
这就能得到checkbox,然后就要可以做你想要做的事了呀!
[解决办法]
直接使用TreeView.SelectedItem,不行么?
[解决办法]
那也可以的啊!
在你注册的CheckBox的事件里面,
CheckBox cb=new CheckBox ();
TreeViewItem tvi =cb.Parent as TreeViewItem;
[解决办法]
最简单的方法(这样可能导致内存泄漏,慎用。在释放时,注意将tag的引用去掉):
CheckBox pCheckB = new CheckBox();
pTVItem.Header = pCheckB;
pCheckB.Tag = pTVItem;//将treeviewitem保存在checkbox的tag里
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
CheckBox pCB = sender as CheckBox;
TreeViewItem parentTreeViewItem =pCB.Tag as TreeViewItem;//通过tag获取treeviewitem
//DependencyObject parent = VisualTreeHelper.GetParent(pCB);//获取依赖的父级对象
//TreeViewItem parentTreeViewItem = parent as TreeViewItem;//此处出错!
....
}