<TreeView Background="{StaticResource LightGradientBrush}" Name="TVOffice" Margin="3">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal" Margin="4">
<CheckBox Height="23" IsThreeState="False" Name="chkbox" IsChecked="{Binding IsSelected}" Click="chkbox_Click" />
<!---->
<TextBlock Height="23" FontFamily="Microsoft YaHei" HorizontalAlignment="Left" VerticalAlignment="Center" Text="{Binding Name}" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
这里定义了一个treeview控件,其中的checkbox取名叫chkbox,有一个chkbox_Click事件
void chkbox_Click(object sender, RoutedEventArgs e)
{
CheckBox chkbox = sender as CheckBox;
DependencyObject parent = VisualTreeHelper.GetParent(VisualTreeHelper.GetParent(chkbox)); //找到chkbox的ContentPresenter
ContentPresenter tvi = parent as ContentPresenter;
if (tvi != null)
{
List<OfficeTreeNode> list = TVOffice.ItemsSource as List<OfficeTreeNode>;
OfficeTreeNode node = tvi.DataContext as OfficeTreeNode;
TreeViewItem tvitem = TreeViewHelper.FindTreeViewItemContainer(this.TVOffice, node);
tvitem.IsSelected = true;
}
}
这是完整的Click方法
思路就是找到CheckBox的ContentPresenter,然后获取DataContext,再通过DataContext来获取选中的treeviewitem。其中,FindTreeViewItemContainer方法具体如下,功能就是treeview控件中找到info对象对应的treeviewitem。
public static TreeViewItem FindTreeViewItemContainer(ItemsControl root, object info)
{
if (root == null) { return null; }
TreeViewItem tvi = root.ItemContainerGenerator.ContainerFromItem(info) as TreeViewItem;
if (tvi == null)
{
if (root.Items != null)
{
foreach (var item in root.Items)
{
tvi = FindTreeViewItemContainer(root.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem, info);
if (tvi != null)
{
break;
}
}
}
}
return tvi;
}
找到treeviewitem以后就可以在点击CheckBox的同时选中相应的treeviewitem了。
刚开始学习,做一点记录,每天进步一点。