Click here to Skip to main content
15,911,315 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created a treeview in WPF form in C# to display all directories of the computer. Now i want to add checkboxes on the left before icons to select multiple directories. Can anyone give a link or anything that can help me to understand and implement checkboxes according to my requirement.

Thanks
Posted

Use DataTemplate for TreeView. Before this, create a class for Folder(directory) with two properties,
1. FolderName - string property - to hold Folder's name.
2. CheckedStatus - bool property - to hold the selection status.
Add some more properties as per your requirement.
and now Folder class would be,
C#
public class Folder
{
    public string FolderName { get; set; }
    public bool CheckedStatus { get; set; }
    //...............
    ...............//
}

And, define a DataTemplate in TreeView's XAML source like following,
XML
<treeview name="FolderTree" margin="10,37,5,10">
   <treeview.resources>
      <datatemplate datatype="{x:Type local:Folder}">
         <stackpanel orientation="Horizontal">
            <checkbox ischecked="{Binding CheckedStatus, Mode=TwoWay}" />
            <image margin="4,0,0,0" width="15" height="15" source="Images/folder.png" />
            <textblock margin="4,0,0,0" text="{Binding FolderName}" />
         </stackpanel>
      </datatemplate>
   </treeview.resources>
</treeview>

Above code defines a DataTemplate for TreeView, the defined DataTemplate contains,
CheckBox - to allow users to select folders,
Image - to display folder image and
TextBlock - to show folder name.
These controls are wrapped into a StackPanel. Here Image is optional.

Now create an ObservableCollection to hold folders.
C#
ObservableCollection<Folder> FolderCollection = new ObservableCollection<Folder>();

Add Folders of your specified location to this collection by creating objects for Folder Class.
C#
foreach (DirectoryInfo dir in YourDirectoryObject.GetDirectories())
{
   Folder objFolder = new Folder();
   objFolder.FolderName = dir.Name;
   FolderCollection.Add(objFolder);
}

assign the prepared ObservableCollection FolderCollection to treeview.
C#
FolderTree.ItemsSource = FolderCollection;


This will gives you a treeview with checkbox for selection. And you can loop through your FolderCollection to get selected Folders by checking CheckedStatus property.
 
Share this answer
 
v2
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900