2010-04-19 155 views
4

我實現了一個WPF按需樹形視圖,如this(非常好)文章中所述。 在上述解決方案中,使用虛擬元素來保留圖標/樹視圖項目行爲的擴展+。當用戶點擊擴展器時,虛擬項目被替換爲實際數據。WPF TreeView數據綁定隱藏/顯示展開/摺疊圖標

我想通過向我的支持TreeNodeViewModel添加屬性public bool HasChildren { get { ... } }來優化模型。

問:
我如何可以綁定這個屬性爲隱藏/顯示擴展圖標(XAML)?我無法找到合適的觸發器/設置器組合。
(INotifyPropertyChanged正確實施。)

感謝您的時間。

更新1:
我想用用虛設的元素的我的財產public bool HasChildren代替
確定一件物品是否有孩子有點貴,但仍比取孩子便宜。

回答

2

朱利安,

這是一個非常好的問題。你爲什麼不嘗試編寫自己的樹視圖項目? :)我的意思是,不是從頭開始,只是從現有的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> 

正如你所看到的,第一個項目是一個普通的一個,第二個是你的自定義一個。請注意,它有一個孩子。接下來,你可以HasChildren屬性綁定到一些布爾對象在你的視圖模型或只是簡單地通過設置HasChildren從代碼測試我的自定義類來上述XAML背後:現在

xyz.HasChildren = false; 

,儘管你的元素有一個孩子,展開按鈕不顯示,所以這意味着,我的自定義類工作。

我希望我幫你,但隨時問,如果你有任何問題。

Piotr。

1

後迅速尋找到Josh的代碼,我發現這個構造:

protected TreeViewItemViewModel(TreeViewItemViewModel parent, bool lazyLoadChildren) 
{ 
    _parent = parent; 

    _children = new ObservableCollection<TreeViewItemViewModel>(); 

    if (lazyLoadChildren) 
     _children.Add(DummyChild); 
} 

所以,如果你通過false從你繼承的ViewModel類lazyLoadChildren參數,+圖標不應該出現,因爲DummyChild不添加。由於您似乎知道您的物品是否有子女,因此您應該能夠通過lazyLoadChildren財產的適當價值。或者我錯過了什麼?