Home > Back-end >  Bind TabControl page selection to a set of RadioButtons with MVVM
Bind TabControl page selection to a set of RadioButtons with MVVM

Time:09-01

I have four RadioButtons in one column and a TabControl in another column with four tab pages. What is the best way to bind the SelectedIndex of the TabControl to the checked state of the RadioButtons to allow users to select a tab page by clicking the RadioButton? Ideally, I want to use Microsoft CommunityToolkit.MVVM.

CodePudding user response:

You can bind the IsSelected property of TabItem to the IsChecked property of RadioButton:

<Grid>
   <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto"/>
      <ColumnDefinition/>
   </Grid.ColumnDefinitions>
   <StackPanel Grid.Column="0">
      <RadioButton x:Name="RadioButton1" GroupName="TabRadioButtons" Content="Tab 1"/>
      <RadioButton x:Name="RadioButton2" GroupName="TabRadioButtons" Content="Tab 2"/>
      <RadioButton x:Name="RadioButton3" GroupName="TabRadioButtons" Content="Tab 3"/>
      <RadioButton x:Name="RadioButton4" GroupName="TabRadioButtons" Content="Tab 4"/>
   </StackPanel>
   <TabControl Grid.Column="1">
      <TabItem Header="Tab 1" IsSelected="{Binding IsChecked, ElementName=RadioButton1}"/>
      <TabItem Header="Tab 2" IsSelected="{Binding IsChecked, ElementName=RadioButton2}"/>
      <TabItem Header="Tab 3" IsSelected="{Binding IsChecked, ElementName=RadioButton3}"/>
      <TabItem Header="Tab 4" IsSelected="{Binding IsChecked, ElementName=RadioButton4}"/>
   </TabControl>
</Grid>
  • Related