treeview Multibinding in wpf
-
30-09-2019 - |
Question
I want to bind a treeview to a class like this one:
public class Folder : Base_FileFolder
{
public Folder()
{
Folders = new ObservableCollection<Folder>();
Files = new ObservableCollection<File>();
}
public ObservableCollection<Folder> Folders { get; set; }
public ObservableCollection<File> Files { get; set; }
}
the other classes ares:
public class File : Base_FileFolder
{
}
public class Base_FileFolder : DependencyObject
{
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Base_FileFolder), new UIPropertyMetadata(""));
}
How can I create a treeview that shows Files and Folders collection
I want to use something like this:
<HierarchicalDataTemplate
DataType="{x:Type model:Folder}"
ItemsSource="{Binding Childs}">
<DockPanel>
<Label Content="{Binding Name}"/> </DockPanel>
</HierarchicalDataTemplate>
so I get Somethign like this:
rootFolder
|
|-File
|-File
|-Folder
|-File
|-File
|-Folder
|-File
Solution
What exactly is your question? How to combine them? CompositeCollection
.
EDIT: as mentioned in the comments, my Intuipic application does something very similar to what you're requesting. Here's a screenshot:
OTHER TIPS
This is quite easy, considering your constellation.
First: Adjust your classes. You do not need two separate Lists for files and folders in the folders class. Just use one IList<Base_FileFolder>
inside the Base_FileFolder class (good OOP) and call it Children!
Then you'll need only two more steps:
Two HierarchicalDataTemplates
<HierarchicalDataTemplate DataType="{x:Type FolderNode}" ItemsSource="{Binding Path=Children}"> <Grid> <TextBlock Text="{Binding FolderName}" /> </Grid> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type FileNode}" ItemsSource="{Binding Path=Children}"> <Grid> <TextBlock Text="{Binding FileName}" /> </Grid> </HierarchicalDataTemplate>
And a TreeView like this
<TreeView Name="TreeViewFileTree" ItemsSource="{rootFolder.Children}" />
That's it. WPF's strength is its simplicity.
You need to use You'll need 3 things:
- a HierarchicalDataTemplate, like you have, to do parent+children, and template the folders. you MIGHT be able to use a CompositeCollection here to merge the folders+files, but i'm not sure about that...you might have to add another property to your folder class that returns the union of files and folders and call it "Children" or whatever...
- A DataTemplate to template files in the tree
- A TemplateSelector to tell the tree to switch between templates depending on the item in the tree. Instead of setting an ItemTemplate on the tree, set the ItemTemplateSelector to this.