1.TreeView的静态扩展类(借鉴http://www.cnblogs.com/sayo/archive/2008/07/23/1249804.html)
public static class ExtensionMethods
{
public static void CollapseOtherItems(this System.Windows.Controls.TreeView treeView, SystemTagNodes selectedNode)
{
CollapseItems(treeView, selectedNode);
}
private static void CollapseItems(ItemsControl control, SystemTagNodes selectedNode)
{
if (control == null)
{
return;
}
foreach (Object item in control.Items)
{
System.Windows.Controls.TreeViewItem treeItem = control.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
if (treeItem == null || !treeItem.HasItems)
{
continue;
}
if (selectedNode.Tag.StartsWith((item as SystemTagNodes).Tag))
treeItem.IsExpanded = true;
else
treeItem.IsExpanded = false;
CollapseItems(treeItem as ItemsControl, selectedNode);
}
}
在网上搜了很多方法,绑定的数据源在折叠时找不到遍历项;唯有此法可解
2.递归的效果是,当某一项的子项很多,为了用户不至于展开过多使空间变得很小,所以让其他同级项折叠
3.在XMAL中添加结点选择事件 TreeViewItem.Selected="tree_Selected"
private void tree_Selected(object sender, RoutedEventArgs e)
{
var item = tree.SelectedItem;
if (item != null && item is SystemTagNodes)
this.tree.CollapseOtherItems(item as SystemTagNodes);
}
4.效果如下
============>