Milos
Milos

Reputation: 3

Change Visibility of Grid on Button Click in Xaml

I am trying to find some way to when a button (Menu) is clicked, it changes the visibility of a Grid (Submenu) with a Trigger in XAML. I made it in vb.net but I wonder if it's easier to do in XAML?

Private Sub ShowSubmenu(SubmenuSettings e As Grid)
        Dim bk As Integer = VisualTreeHelper.GetChildrenCount(MainGrid)
        For i = 0 To bk - 1
            Dim g As Object = VisualTreeHelper.GetChild(MainGrid, i)
            If TypeOf g Is Grid Then g.Visibility = Visibility.Hidden
        Next
        SubmenuSettings.Visibility = Visibility.Visible
    End Sub

Private Sub Visibility(sender As Object)
        If sender Is btn1 Then
            ShowSubmenu(pdm1)
        End If
End Sub

Upvotes: 0

Views: 6393

Answers (2)

tabby
tabby

Reputation: 1918

You can use ToggleButton instead of Button, the idea is to switch Grid Visibility based on IsChecked Property of a ToggleButton.

<Grid  Height="100" Width="100" Background="Green">
   <Grid.Style>
      <Style TargetType="Grid">
          <Setter Property="Visibility" Value="Collapsed"/>
          <Style.Triggers>
             <DataTrigger Binding="{Binding IsChecked,ElementName=btnFirst}" Value="True">
                 <Setter Property="Visibility" Value="Visible"/>
              </DataTrigger>
          </Style.Triggers>
       </Style>
   </Grid.Style>
</Grid>

 <ToggleButton x:Name="btnFirst" Content="BtnFirst" Height="100" Width="100" />

Upvotes: 1

MaxB
MaxB

Reputation: 438

You can give your Grid a " x:Name="gridName" ", then from code when clicking on button, do "gridName.Visibility = Visibility.Collapsed" (Collapsed or Hidden, as you wish). "

Upvotes: 0

Related Questions