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:
I want to fill a WPF TreeView from this array. The TreeView should show the folders like in an explorer view.
Thank you. Marco
If someone has the same problem, here is how I solved it. I created a TreeView in XAML that looks like this:
<TreeView x:Name="tvw" ItemsSource="{Binding}" HorizontalAlignment="Left" Height="798" Margin="10,50,0,0" VerticalAlignment="Top" Width="600">
<TreeView.ItemContainerStyle>
<Style>
<Setter Property="TreeViewItem.IsExpanded" Value="True"/>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:_Folder}" ItemsSource="{Binding Path=SubFolders}">
<TextBlock Text="{Binding Path=Name}" ToolTip="{Binding Path=FullPath}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
In the code I created one class that holds the folders, the structure is build by the treeview itself:
Public Class _Folder
Public Property Name As String
Public Property FullPath As String
Public ReadOnly Property SubFolders As List(Of _Folder) = New List(Of _Folder)()
End Class
The following code iterates through the list (of String) with my folders:
Dim lstFolders As New List(Of _Folder)
Dim RootFolder As New _Folder
For Each f In _items
If f.Contains("\\") Then f = f.Replace("\\", ":")
Dim drive = f.Split(":")(0)
Dim path = f.Split(":")(1)
'If String.IsNullOrEmpty(drive) Then Continue For
RootFolder.Name = drive
Dim charSeparators As Char() = New Char() {System.IO.Path.DirectorySeparatorChar}
Dim pathSplit() As String = path.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries)
Dim currentFolder As _Folder = RootFolder
For Each level In pathSplit
If String.IsNullOrEmpty(level) Then Continue For
Dim foundFolder = (From x In currentFolder.SubFolders Where x.Name = level Select x).FirstOrDefault
If foundFolder Is Nothing Then
foundFolder = New _Folder
foundFolder.Name = level
If f.StartsWith(":") Then 'Netzwerkpfad
foundFolder.FullPath = (f.Substring(0, f.IndexOf(level)) & level).Replace(":", "\\")
Else 'Pfad mit Laufwerksbuchstaben
foundFolder.FullPath = f.Substring(0, f.IndexOf(level)) & level
End If
currentFolder.SubFolders.Add(foundFolder)
End If
currentFolder = foundFolder
Next
Next
lstFolders.Add(RootFolder)