2016-11-28 102 views
-1

這是我第一次在WPF應用程序中使用TreeView控件,並且變得比我想象的更加困難。無法綁定WPF TreeView

我的TreeView必須由MyGroup和MyList類填充。 MyGroup可以有零個或幾個MyGroup子級和一個或多個MyList子級實例。

所有層次結構當前存儲在一個靜態MyGroup實例(RootGroup)中。

我的目標是綁定這個實例,因爲當RootGroup的子項被修改時,樹視圖被更新。

更多的用戶可以在TreeView中拖放組和列表來修改層次結構,RootGroup也會被更新。

我已經閱讀了一些關於TreeViewControl的教程,但是我從來沒有見過有人做過這樣的可編輯TreeView。

我需要一些ViewModel來做到這一點嗎? 你有關於這種TreeView控件的例子嗎?

編輯: 這就是我所做的,但沒有在樹視圖中顯示。

public class VecViewModelBase : INotifyPropertyChanged 
    { 
     public event PropertyChangedEventHandler PropertyChanged; 

     public void OnPropertyChanged(string propname) 
     { 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs(propname)); 
      } 
     } 
    } 

public class VecGroup : VecViewModelBase 
{ 
    public string Name { get; set; } 
    private ObservableCollection<VecGroup> _groups; 
     public ObservableCollection<VecGroup> Groups 
     { 
      get { return _groups; } 
      set 
      { 
       _groups = value; 
       OnPropertyChanged("Groups"); 
      } 
     } 

     private ObservableCollection<VecList> _lists; 
     public ObservableCollection<VecList> Lists 
     { 
      get { return _lists; } 
      set 
      { 
       _lists = value; 
       OnPropertyChanged("Lists"); 
      } 
     } 

     public IList Children 
     { 
      get 
      { 
       var c = new CompositeCollection(); 
       c.Add(new CollectionContainer { Collection = Groups }); 
       c.Add(new CollectionContainer { Collection = Lists }); 
       return c; 
      } 
     } 
} 
public class VecList : VecViewModelBase 
{ 
    public string Name { get; set; } 
} 

MyTreeView.xaml.cs

public partial class MyTreeView : UserControl 
{ 
    public ObservableCollection<VecGroup> VecRoot; 
    public MyTreeView() 
    { 
     InitializeComponent(); 

     VecRoot = new ObservableCollection<VecGroup>() { new VecGroup() { Name = "Test" } }; 
    } 
} 

MyTreeView.xaml

<UserControl.DataContext> 
    <local:MyTreeView/> 
</UserControl.DataContext> 

<TreeView ItemsSource="{Binding VecRoot}" x:Name="ExplorerView"> 
    <TreeView.Resources> 
     <HierarchicalDataTemplate DataType="{x:Type vec:VecGroup}" ItemsSource="{Binding Children}"> 
      <Label Content="{Binding Name}"/> 
     </HierarchicalDataTemplate> 

     <DataTemplate DataType="{x:Type vec:VecList}"> 
      <Label Content="{Binding Name}"/> 
     </DataTemplate> 
    </TreeView.Resources> 
</TreeView > 

謝謝。

+0

是的,用viewmodel做。 –

回答

0

看看這個項目:Simplifying the WPF TreeView by Using the ViewModel Pattern 在這個項目中,它們綁定了TreeView並在其中搜索項目。

+0

謝謝,但我已閱讀此帖。我用我的代碼更新了我的問題,以便更好地瞭解我的項目,該項目必須使用異構類型數據綁定以及拖放功能。 – mickaelb91