I am struggling with this and hope someone can help me solving. I have an array of string that are directories. This is an example of my array:
- c:\temp\freigabe
- c:\temp\ftptest
- c:\temp\ftptest\testen
- c:\temp\in
- c:\temp\in - Kopie
- c:\temp\in - Kopie\1
- c:\temp\in - Kopie\1\yyy
- c:\temp\in - Kopie\1\yyy\yyyyy
- c:\temp\in - Kopie\2
- c:\temp\in2
- c:\temp\ipadb
- c:\temp\out
- c:\temp\out2
- c:\temp\Processes2
- c:\temp\Processes2\Kassenbelege
- c:\temp\Processes2\Kassenbelege\images
- c:\temp\Processes2\Posteingang
- c:\temp\Processes2\Posteingang\images
- c:\temp\Processes2\Rechnungen
- c:\temp\Processes2\Rechnungen\images
- c:\temp\Processes2\Rechnungen\images\backup
- c:\temp\test
I want to fill a WPF TreeView from this array. The TreeView should show the folders like in an explorer view.
Thank you. Marco
CodePudding user response:
WPF works around the idea of data binding. Assuming that you have a collection, you are expected to bind the TreeView to the item collection. If you have, for example:
Class TreeViewItem
Public Property DisplayText As String
End Class
And if you have a TreeView defined like this:
<TreeView Name="FileListView" ItemsSource="{Binding}" />
Then you can explicitly bind the collection, e.g.
Class MyWindow
Dim _items As New ObservableCollection(Of TreeViewItem)
'...
Public Sub New()
InitializeComponent()
'...
FileListView.DataContext = _items
'...
End Sub
'...
End Class
I think you may need to define an item template for the TreeView so that it knows how to display your items as well, which would be something like this inside the TreeView definition in xaml:
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding}">
<TextBlock Text="{Binding DisplayText}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
In this case, I manually set the datacontext on the TreeView, but the more common approach in WPF would be to have a datacontext for the form as a whole, and then bind the treeview to a property on the form-level datacontext type.
CodePudding user response:
TreeViews require a hierarchical structure, not a flat list of items.
Something like
public class Folder
{
public string Name { get; set; }
public List<Folder> SubFolders { get; } = new List<Folder>();
}
which you will have to create for each item to be displayed.
The ItemsSource
property of the TreeView
control can then be assigned (or bound to) a collection of Folder items, which would form the root nodes of the tree.