views:

86

answers:

1

I'm binding TreeView. My reason is treeview level 0 is unselectable. When i click level 0 treeviewitem, current item must be collapse and first child item must be selected.

├ Item 1   //<- level 0. this item must be unselectable
├─ Child Item 11 //<- level 1
├─ Child Item 12
├ Item 2   //<- level 0. When i click this item, that is automatically collapse
├─ Child Item 21
├─ Child Item 22

How to do this using style?

+2  A: 

I'd do it in my view model. The view model for level 0 items would have:

public bool IsSelected
{
    get { return false; }
    set
    {
        // error checking is omitted
        Children[0].IsSelected = value;

        // let WPF know that IsSelected may have changed from what it's expecting
        this.Dispatcher.BeginInvoke((ThreadStart)delegate
        {
            this.OnPropertyChanged(() => this.IsSelected);
        });
    }
}

Your XAML would look like:

<TreeView>
    <TreeView.ItemContainerStyle>
        <Style TargetType="TreeViewItem">
            <Setter Property="IsSelected" Value="{Binding IsSelected}"/>
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>

Now whenever the user clicks on a level-one item, the VM will refuse to be selected and instead select its first child item.

You can use exactly the same technique to handle your requirements around collapsing levels.

HTH,
Kent

Kent Boogaart