代码之家  ›  专栏  ›  技术社区  ›  Julian Lettner

WPF TreeView数据绑定以隐藏/显示展开/折叠图标

  •  4
  • Julian Lettner  · 技术社区  · 15 年前

    this (非常好)文章。 在上述解决方案中,使用虚拟元素来保留扩展 + 图标/树视图项目行为。当用户单击扩展器时,虚拟项将替换为真实数据。

    我想通过添加一个属性来优化模型 public bool HasChildren { get { ... } } 为了我的支持 TreeNodeViewModel .



    (INotifyPropertyChanged已正确实现。)

    更新1:
    public bool HasChildren 相反
    确定一个项目是否有子项有些昂贵,但仍然比获取子项便宜得多。

    2 回复  |  直到 15 年前
        1
  •  1
  •   Piotr Justyna    15 年前

    朱利安,

    这真是个好问题。为什么不尝试编写自己的树视图项?:)我的意思是,不是从头开始,只是从现有的TreeViewItem派生并添加属性。我已经准备了一个快速的例子,但请随意修改它,因为你想(并提出问题,如果有什么是不完全清楚)。我们开始吧:

    public class TreeViewItem_CustomControl : TreeViewItem
    {
        static TreeViewItem_CustomControl()
        {
            HasChildrenProperty = DependencyProperty.Register("HasChildren", typeof(Boolean), typeof(TreeViewItem_CustomControl));
        }
    
        static DependencyProperty HasChildrenProperty;
    
        public Boolean HasChildren
        {
            get
            {
                return (Boolean)base.GetValue(HasChildrenProperty);
            }
    
            set
            {
                if (value)
                {
                    if (this.Items != null)
                    {
                        this.Items.Add(String.Empty); //Dummy item
                    }
                }
                else
                {
                    if (this.Items != null)
                    {
                        this.Items.Clear();
                    }
                }
    
                base.SetValue(HasChildrenProperty, value);
            }
    
        }
    }
    

    这是您自定义TreeViewItem的代码。现在让我们在XAML中使用它:

    <TreeView>
        <TreeViewItem Header="qwer">
            Regulat tree view item.
        </TreeViewItem>
        <CustomTree:TreeViewItem_CustomControl x:Name="xyz" Header="temp header" Height="50">
            <TreeViewItem>Custom tree view item, which will be removed.</TreeViewItem>
        </CustomTree:TreeViewItem_CustomControl>
    </TreeView>
    

    如你所见,第一件是普通的,第二件是定制的。请注意,它有一个孩子。接下来,您可以绑定 属性设置为ViewModel中的某个布尔对象,或者只需通过将HasChildren设置为 从上述XAML背后的代码:

    xyz.HasChildren = false;
    

    我希望我能帮到你,但如果你有任何问题,尽管问。

    彼得。

        2
  •  1
  •   gehho    15 年前

    在快速查看了Josh的代码之后,我发现了这个构造函数:

    protected TreeViewItemViewModel(TreeViewItemViewModel parent, bool lazyLoadChildren)
    {
        _parent = parent;
    
        _children = new ObservableCollection<TreeViewItemViewModel>();
    
        if (lazyLoadChildren)
            _children.Add(DummyChild);
    }
    

    false 对于 lazyLoadChildren 懒汉儿童 财产。还是我遗漏了什么?