Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF toggle panel visibility

I have two panels, only one should be visible at the same time. I change between them by clicking a button, one on each panel.

Is there a nice way to do this in xaml without codebehind or viewmodel?

like image 842
Karsten Avatar asked Jun 08 '11 12:06

Karsten


1 Answers

It's actually possible, however quite tricky.

My example works without any code-behind, actually without any value converters, too.

Here is the code: (now simplified version, thanks to @H.B. for ideas)

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:sys="clr-namespace:System;assembly=mscorlib"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Page.Resources>
    <Style x:Key="RBToggleButtonStyle" TargetType="RadioButton">
      <Setter Property="Template">
         <Setter.Value>
           <ControlTemplate>
              <ToggleButton
                 IsChecked="{Binding IsChecked, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
                 Content="{Binding Content, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" />
           </ControlTemplate>
         </Setter.Value>
       </Setter>
       <Setter Property="Width" Value="150"/>
       <Setter Property="Height" Value="25"/>
       <Setter Property="HorizontalAlignment" Value="Right"/>
       <Setter Property="VerticalAlignment" Value="Bottom"/>
       <Setter Property="Margin" Value="15"/>
       <Setter Property="Content" Value="Hide"/>
    </Style>
    <Style x:Key="MyBorderStyle" TargetType="Border">
      <Style.Triggers>
        <DataTrigger Binding="{Binding IsChecked}" Value="True">
          <Setter Property="Visibility" Value="Hidden"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Page.Resources>
  <Grid>
    <Grid.ColumnDefinitions>
      <ColumnDefinition/>
      <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Border Background="Green" Grid.Column="0" Style="{StaticResource MyBorderStyle}" DataContext="{Binding ElementName=greenB}">
      <RadioButton x:Name="greenB" GroupName="x" Style="{StaticResource RBToggleButtonStyle}"/>
    </Border>
    <Border Background="Red" Grid.Column="1" Style="{StaticResource MyBorderStyle}" DataContext="{Binding ElementName=redB}">
      <RadioButton x:Name="redB" GroupName="x" Style="{StaticResource RBToggleButtonStyle}"/>
    </Border>
  </Grid>
</Page>

The idea of using ToggleButtons is stolen from some other question at SO

like image 153
Vlad Avatar answered Sep 29 '22 08:09

Vlad