views:

444

answers:

1

Hi! I'm trying to add checkboxes to the leaf nodes in a TreeView in WPF. I know how to do this if we have a fixed number of levels in the hierarchy and using a HierarchicalDataTemplate for each level. But what to do when I want this:
-Node 1
-- Node 1a (leaf node with checkbox)
-- Node 1b
--- Node 1bI (leaf node with checkbox)
-Node 2
-- Node 2a (leaf node with checkbox)

I set the DataContext in the code file to a DataTable. Just one table, with a relation to it self.

DataContext = ds.MyDataTable;

XAML:

<UserControl x:Class="JostyWpfControls.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Height="240" Width="312">
    <UserControl.Resources>
        <HierarchicalDataTemplate x:Key="myTemplate" 
            ItemsSource="{Binding myDatasetRelation}">
            <CheckBox IsChecked="{Binding IsChosen}">
                <TextBlock Text="{Binding Description}"/>
            </CheckBox>
        </HierarchicalDataTemplate>
    </UserControl.Resources>
    <Grid>
        <TreeView x:Name="treeView" 
            ItemsSource="{Binding}" 
            ItemTemplate="{StaticResource myTemplate}">
        </TreeView>
    </Grid>
</UserControl>

This is working, but gives me a chechbox to all nodes. I just want the leaf nodes to have a checkbox.

+1  A: 

You could use a trigger in the data template to determine whether the checkbox should be visible:

<HierarchicalDataTemplate x:Key="myTemplate" 
                          ItemsSource="{Binding myDatasetRelation}">
  <StackPanel>
    <CheckBox x:Name="CheckBox" IsChecked="{Binding IsChosen}" 
              Content="{Binding Description}" />
    <TextBlock x:Name="LeafLabel" Text="{Binding Description}"
               Visibility="Collapsed" />
  </StackPanel>
  <HierarchicalDataTemplate.Triggers>
    <DataTrigger Binding="{Binding myDatasetRelation.Count}" Value="0">
      <Setter TargetName="CheckBox" Property="Visibility" Value="Collapsed" />
      <Setter TargetName="LeafLabel" Property="Visibility" Value="Visible" />
    </DataTrigger>
  </HierarchicalDataTemplate.Triggers>
</HierarchicalDataTemplate>

I'm not sure whether the value bound to via myDatasetRelation has a Count property, but if not then you could use Length or find some other way to determine whether it's empty or not (perhaps using an IValueConverter if no simpler approach is available.

Drew Noakes
Just pasted your code and this works swell! Thanks!
Jostein
You're welcome. I'm glad it worked as I typed it from memory which often doesn't work first time.
Drew Noakes