Home > Net >  WPF C# - Bind tab selection to treeView selection
WPF C# - Bind tab selection to treeView selection

Time:09-01

How do I bind a tabItem IsSelected property to a treeView Node selection via index or reference?

I want to be able to click on a treenode that will auto select a tabItem within a tabControl

CodePudding user response:

MainWindow.xmal

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp1"
        Height="600" Width="800">
    <StackPanel>
        <TreeView Width="200" Height="200">
            <TreeViewItem Header="Items">
                <TreeViewItem x:Name="item1" Header="Tab1"/>
                <TreeViewItem x:Name="item2" Header="Tab2"/>
            </TreeViewItem>
        </TreeView>
        <TabControl Height="200" Width="200">
            <TabItem Header="Tab1" IsSelected="{Binding ElementName=item1, Path=IsSelected}">
                <TextBox/>
            </TabItem>
            <TabItem Header="Tab2" IsSelected="{Binding ElementName=item2, Path=IsSelected}">
                <TextBox/>
            </TabItem>
        </TabControl>
    </StackPanel>
</Window>

combined with the previous question...

https://stackoverflow.com/a/73563420/19891367

<Window x:Class="WpfApp1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfApp1"
            Height="600" Width="800">
    <StackPanel>
        <TreeView x:Name="treeView" Width="200" Height="200">
            <TreeViewItem Header="Tab1">
                <TreeViewItem Header="Tab1-1"/>
                <TreeViewItem Header="Tab1-2"/>
            </TreeViewItem>
            <TreeViewItem Header="Tab2">
            </TreeViewItem>
        </TreeView>
        <local:UserControl1 Height="200" Width="200"
                            DataContext="{Binding ElementName=treeView}">
            <local:UserControl1.TabItem>
                <TabItem Header="Tab1" IsSelected="{Binding Items[0].IsSelected}"/>

                <TabItem Header="Tab2" IsSelected="{Binding Items[1].IsSelected}"/>

                <TabItem Header="Tab1-1" IsSelected="{Binding Items[0].Items[0].IsSelected}"/>
            
                <TabItem Header="Tab1-2" IsSelected="{Binding Items[0].Items[1].IsSelected}"/>
            </local:UserControl1.TabItem>
        </local:UserControl1>
    </StackPanel>
</Window>
  • Related