I have created a FOLDER BROWSER control in WPF, and is working fine, but for only one drive that I hard code.
The document I followed to do so is :
http://msdn.microsoft.com/en-us/library/bb546972%28v=vs.90%29.aspx
I want to make it list all drives in the system in the treeview instead of only one.
<Window.Resources>
<ObjectDataProvider x:Key="RootFolderDataProvider">
<ObjectDataProvider.ObjectInstance>
<folderExplorer:FolderExplorer FullPath="e:\" />
</ObjectDataProvider.ObjectInstance>
</ObjectDataProvider>
<HierarchicalDataTemplate
DataType = "{x:Type folderExplorer:FolderExplorer}"
ItemsSource = "{Binding Path=SubFolders}">
<TextBlock Text="{Binding Path=Name}" />
</HierarchicalDataTemplate>
</Window.Resources>
<TreeView Grid.Column="0"
Name="RootTreeView"
Background="AliceBlue"
Foreground="Black" Grid.RowSpan="3" Margin="0,0,0,169">
<TreeViewItem Header="Browse">
<TreeViewItem.ItemsSource>
<Binding Source="{StaticResource RootFolderDataProvider}">
<Binding.Path>SubFolders</Binding.Path>
</Binding>
</TreeViewItem.ItemsSource>
</TreeViewItem>
</TreeView>
If I populate the treeview in the code behind, all my other code is breaking..
Any suggestion on how to make this list all drive will be very helpful.
First, we are going to need a new class, call it "DriveExplorer". I am keeping the "Folder" name from the linked sample, from your XAML you may need to replace it with "FolderExplorer".
First, the code:
Now for what it does. Just like "Folder" we declare a list of
ObservableCollection<Folder>
to store our "drives" in. For all intents and purposes, a drive is just a folder we get in a different way. Then, we get the list of drives on the system usingDriveInfo.GetDrives()
.We then iterate over the whole collection using a foreach (this does the same thing as the for loop in the sample code) using "drive" as our iteration variable (MSDN). I assumed that we just want hard drives, so we check the DriveType for "Fixed". If we don't care about the type, this check could be removed. For a full reference on this function, see MSDN. Finally, we make a new "Folder" with the path set to the drive letter, just like you do in your XAML (and the sample does in its constructor).
Now for the XAML, we will need a very similar Data Template to the one you already have(this is in addition to the existing one):
Then we just need to change the data source to a "DriveExplorer":
This should give you the output you want. Let me know if I need to make any corrections or can clarify anything!