Search code examples
wpfxamlmvvmdata-bindingtogglebutton

Event handler on togglebutton


I am creating ToggleButton and if I do not check it, it looks this:

ToggleButton as swith that is unchecked (off).

If I check it, it looks like this:

ToggleButton as swith that is checked (on) with a ComboBox next to it.

I use MaterialDesign and this is my code:

<Grid Grid.Row="0" VerticalAlignment="Center">
    <TextBlock  Text="Máy in hóa đơn :"
       Foreground="White" Margin="15,20,0,0"/>
    <ToggleButton   VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0,20,0,0"/>
</Grid>

I want to show the ComboBox if the ToggleButton is checked, otherwise hide it. I don't know how to do so. I do not want to write in code behind.


Solution

  • You can assign an x:Name to the ToggleButton and create a Style for the ComboBox which uses a DataTrigger that changes its Visibility depending on the IsChecked property of the ToggleButton. The binding uses the ElementName to refer to the ToggleButton.

    <StackPanel Orientation="Horizontal">
       <TextBlock Text="Máy in hóa đơn :" Foreground="White" Margin="15,20,0,0" />
       <ToggleButton x:Name="MyToggleButton" VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0,20,0,0" />
       <ComboBox VerticalAlignment="Top">
          <ComboBox.Style>
             <Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
                <Setter Property="Visibility" Value="Hidden"/>
                <Style.Triggers>
                   <DataTrigger Binding="{Binding IsChecked, ElementName=MyToggleButton}" Value="True">
                      <Setter Property="Visibility" Value="Visible"/>
                   </DataTrigger>
                </Style.Triggers>
             </Style>
          </ComboBox.Style>
       </ComboBox>
    </StackPanel>
    

    Alternatively, use the built-in BooleanToVisibilityConverter in the Visibility binding.

    <StackPanel Orientation="Horizontal">
       <StackPanel.Resources>
          <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
       </StackPanel.Resources>
       <TextBlock Text="Máy in hóa đơn :" Foreground="White" Margin="15,20,0,0" />
       <ToggleButton x:Name="MyToggleButton" VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0,20,0,0" />
       <ComboBox VerticalAlignment="Top" Visibility="{Binding IsChecked, ElementName=MyToggleButton, Converter={StaticResource BooleanToVisibilityConverter}}"/>
    </StackPanel>