您的位置:首页 > 其它

WPF中展开一个TreeView控件的所有树节点

2008-03-11 10:01 519 查看
       在 Windows Form 应用中,我们碰到需要展开一个TreeView 控件的所有树节点的时候很简单,微软已经替我们提供了ExpandAll 方法,我们只要简单的一行代码tv_QTree.ExpandAll();就可以了。即 System.Windows.Forms 命名空间的 TreeView.ExpandAll 方法 。
       在WPF中,我们会发现,System.Windows.Controls.TreeView 中没有了 ExpandAll 方法。唯一跟展开有关系的属性和方法就是每一个TreeViewItem 中有一个属性IsExpanded 属性。这个属性定义这个节点是否打开。MSDN帮助如下:
       Gets or sets whether the nested items in a TreeViewItem are expanded or collapsed. This is a dependency property.
       这时候如何办呢? 很简单,自己写个递归,遍历这个树的每一个子节点,然后把每一个子节点的 IsExpanded 设置为 true.
       你可以通过以下几个链接看到这个解决方案:
       http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=976861&SiteID=1
       http://shevaspace.spaces.live.com/blog/cns!FD9A0F1F8DD06954!463.entry
       http://blogs.msdn.com/okoboji/archive/2006/09/20/764019.aspx
 
       我们可以在上面解决方案基础上进一步发展。
       用扩展方法来给 System.Windows.Controls.TreeView 类扩展个 ExpandAll方法方法。有关扩展方法的一些基础知识可以参看我之前的博客:C#3.0 中的扩展方法 (Extension Methods)
      我的扩展方法代码如下:
///
/// 郭红俊的扩展方法
///
public static class ExtensionMethods
{
    ///
    ///
    ///
    ///
    public static void ExpandAll(this System.Windows.Controls.TreeView treeView)
    {
        ExpandInternal(treeView);
    }
    ///
    ///
    ///
    ///
    private static void ExpandInternal(System.Windows.Controls.ItemsControl targetItemContainer)
    {
        if (targetItemContainer == null) return;
        if (targetItemContainer.Items == null) return;
        for (int i = 0; i < targetItemContainer.Items.Count; i++)
        {
            System.Windows.Controls.TreeViewItem treeItem = targetItemContainer.Items[i] as System.Windows.Controls.TreeViewItem;
            if (treeItem == null) continue;
            if (!treeItem.HasItems) continue;
            treeItem.IsExpanded = true;
            ExpandInternal(treeItem);
        }
    }
}
 
扩展方法的使用方法也请参看C#3.0 中的扩展方法 (Extension Methods) 提到的注意事项。
 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: