ebattulga
ebattulga

Reputation: 11001

How to create unselectable TreeViewItem in WPF

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?

Upvotes: 4

Views: 2186

Answers (1)

Kent Boogaart
Kent Boogaart

Reputation: 178820

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.

Upvotes: 7

Related Questions