I have a code that displays the files and folders names in a TreeView and put a checkbox from each element. What I don't know how to do is how to know the elements in the TreeView that are selected with the checkboxes.
XAML:
<TreeView Name="treeView" Grid.Row="10" Grid.ColumnSpan="3">
<TreeView.Resources>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Focusable="False" IsChecked="False" VerticalAlignment="Center"/>
<TextBlock Text="{Binding}" Margin="5,0" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</TreeView.Resources>
</TreeView>
Program:
DirectoryInfo di = new DirectoryInfo(folder);
treeView.Items.Add(getTree(di));
public TreeViewItem getTree(DirectoryInfo di)
{
TreeViewItem item = new TreeViewItem();
item.Header = di.Name;
item.FontWeight = FontWeights.Normal;
foreach (DirectoryInfo s in di.GetDirectories())
{
item.Items.Add(getTree(s));
}
foreach (FileInfo fi in di.GetFiles())
{
item.Items.Add(fi.Name);
}
return item;
}
Create your own
TreeViewItem
type:Add instance of this type to the
TreeView
:Bind to the properties of this type in the view:
You could then iterate through the items recursively and check the value of the
IsChecked
property:If you want to take this a step further, you bind the
ItemsSource
property of theTreeView
to anIEnumerable<Node>
property of your view model and iterate through this one instead of theItems
property of theTreeView
control.