tags:

views:

757

answers:

2

I have a two-level hierarchy displayed in a WPF TreeView, but I only want the child nodes to be selectable - basically the top level nodes are for categorisation but shouldn't be selectable by themselves.

Can I achieve this?

Thanks...

+2  A: 

To do so you would need to override the style for treeview. Ideally you will have two types of treeview items one for your top-level nodes (im assuming folders) and another simply for the children, then you should be able to define how each item type in the tree behaves. So create a style for each item type, then for the folder node simply change the trigger for is selected to do nothing.

Bijington
but how would you prevent the treeview from semantically selecting the top level node? hiding the fact that the category is selected with visual styles may not be enough
Rob Fonseca-Ensor
A: 

I've written at attached property that will unselect a treeviewitem as soon as it's selected:

public class TreeViewItemHelper
{
    public static bool GetIsSelectable(TreeViewItem obj)
    {
        return (bool)obj.GetValue(IsSelectableProperty);
    }

    public static void SetIsSelectable(TreeViewItem obj, bool value)
    {
        obj.SetValue(IsSelectableProperty, value);
    }

    public static readonly DependencyProperty IsSelectableProperty =
        DependencyProperty.RegisterAttached("IsSelectable", typeof(bool), typeof(TreeViewItemHelper), new UIPropertyMetadata(true, IsSelectablePropertyChangedCallback));

    private static void IsSelectablePropertyChangedCallback(DependencyObject o, DependencyPropertyChangedEventArgs args)
    {
        TreeViewItem i = (TreeViewItem) o;
        i.Selected -= OnSelected;
        if(!GetIsSelectable(i))
        {
            i.Selected += OnSelected;
        }
    }

    private static void OnSelected(object sender, RoutedEventArgs args)
    {
        if(sender==args.Source)
        {
            TreeViewItem i = (TreeViewItem)sender;
            i.IsSelected = false;
        }
    }
}

Unfortunately you still lose the old selection when you click on an unselectable item :(

Rob Fonseca-Ensor