How to create unselectable TreeViewItem in WPF

落爺英雄遲暮 提交于 2019-12-19 09:15:14

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/2750394/how-to-create-unselectable-treeviewitem-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!