ToggleButton IsChecked trigger

a 夏天 提交于 2019-12-25 05:31:37

问题


I am writing one application where I have a ToggleButton and other few controls on UI. I want to achieve bellow two things when state of ToggleButton is IsChecked.

1) Hide few controls e.g. button1,button2 etc. in below example
2) Change 'Content' of ToggleButton to 'Show'

I can achieve point no 2 but don't know how to access other control and set their properties inside a Trigger. My xaml code is shown below:

<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="108*" />
    <RowDefinition Height="107*" />
    <RowDefinition Height="96*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="209*" />
    <ColumnDefinition Width="161*" />
    <ColumnDefinition Width="133*" />
  </Grid.ColumnDefinitions>
  <ToggleButton x:Name="tg"
                Height="20"
                Width="80"
                Grid.Column="1"
                Margin="2,38,79,49"
                Grid.Row="1">
    <ToggleButton.Style>
      <Style TargetType="{x:Type ToggleButton}">
        <Setter Property="Content"
                Value="Hide" />
        <Style.Triggers>
          <Trigger Property="IsChecked"
                   Value="true">
            <Setter Property="{Binding ElementName=Button1,Path=Content}"
                    Value="Show" />
          </Trigger>
        </Style.Triggers>
      </Style>
    </ToggleButton.Style>
  </ToggleButton>
  <Button Content="Button1"
          Height="23"
          HorizontalAlignment="Left"
          Margin="45,28,0,0"
          Name="button1"
          VerticalAlignment="Top"
          Width="75" />
  <Button Content="Button2"
          Height="23"
          HorizontalAlignment="Left"
          Margin="38,28,0,0"
          Name="button2"
          VerticalAlignment="Top"
          Width="75"
          Grid.Column="1" />
</Grid>

Question: When user clicks on toggle button 'tg' I want to hide 'button1','button2' and when state of toggle button changes to un-check again show the button1.

How can I toggle the visibility of button1 with the ToggleButton's IsChecked property?


回答1:


In your resources declare BoolToVisibilityConverter as given below:

<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVis" />
</Window.Resources>

Then set the visibility of button1 as binding:

    <Button Content="Button1" Height="23" HorizontalAlignment="Left" Margin="45,28,0,0" Name="button1" VerticalAlignment="Top" Width="75" 
            Visibility="{Binding ElementName=tg, Path=IsChecked, Converter={StaticResource BoolToVis}}"/>


来源:https://stackoverflow.com/questions/16634570/togglebutton-ischecked-trigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!