Home > Enterprise >  WPF C# Bind multiple treeViewItems isSelected to tabItem isSelected
WPF C# Bind multiple treeViewItems isSelected to tabItem isSelected

Time:09-02

Building on the Q&A here: WPF C# - Bind tab selection to treeView selection

Is it possible to bind the treeViewItem and all of its children and potential future children to the same tabItem selection?

<TreeViewItem Header="Letters" x:Name="tab1">
   <TreeViewItem Header="a" x:Name="tab1_1"/>
   <TreeViewItem Header="b" x:Name="tab1_2"/>
   <TreeViewItem Header="c" x:Name="tab1_3"/>
   <TreeViewItem Header="d" x:Name="tab1_4"/>
   <TreeViewItem Header="e" x:Name="tab1_5"/>
   <TreeViewItem Header="f" x:Name="tab1_6"/>
</TreeViewItem>

Currently it will deselect the tab when clicking on a child node with this code:

<TabItem x:Name="tabLetters"
    IsSelected="{Binding ElementName=tab1, Path=IsSelected}">
</TabItem>

CodePudding user response:

using SelectedValue and SelectedValuePath.

The TreeViewItem child and parent must have the same Uid.

<Window x:Class="WpfApp1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel>
        <TreeView x:Name="treeView" Height="200" SelectedValuePath="Uid">
        
            <TreeViewItem Header="Letters-1" x:Name="tab1" Uid="Letters-1">
                <TreeViewItem Header="a" Uid="Letters-1"/>
                <TreeViewItem Header="b" Uid="Letters-1"/>
                <TreeViewItem Header="c" Uid="Letters-1"/>
            </TreeViewItem>
        
            <TreeViewItem Header="Letters-2" x:Name="tab2" Uid="Letters-2">
                <TreeViewItem Header="d" Uid="Letters-2"/>
                <TreeViewItem Header="e" Uid="Letters-2"/>
                <TreeViewItem Header="f" Uid="Letters-2"/>
            </TreeViewItem>
        
            <TreeViewItem Header="Letters-3" x:Name="tab3" Uid="Letters-3">
                <TreeViewItem Header="g" Uid="Letters-3"/>
                <TreeViewItem Header="h" Uid="Letters-3"/>
                <TreeViewItem Header="i" Uid="Letters-3"/>
            </TreeViewItem>
        
        </TreeView>
    
        <TabControl x:Name="tabControl" Height="100"
                    SelectedValuePath="Header"
                    SelectedValue="{Binding ElementName=treeView, Path=SelectedValue, Mode=OneWay}">
        
            <TabItem Header="Letters-1"/>

            <TabItem Header="Letters-2"/>

            <TabItem Header="Letters-3"/>

        </TabControl>
    </StackPanel>
</Window>
  • Related