WPF template for yes/no ToggleButton

前端 未结 2 546
天涯浪人
天涯浪人 2021-02-11 05:09

Can anyone help me with a simple template to make a WPF ToggleButton show \"yes\" or \"no\" depending on it\'s toggle state?

I dont want it to look like a button though,

相关标签:
2条回答
  • 2021-02-11 05:43

    You can do this easily with a style:

        <Window x:Class="WpfTest.MainWindow"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <Style x:Key="OnOffToggleStyle" TargetType="ToggleButton">
                <Style.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter Property="Content">
                            <Setter.Value>
                                <TextBlock Text="Yes"/>
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                    <Trigger Property="IsChecked" Value="False">
                        <Setter Property="Content">
                            <Setter.Value>
                                <TextBlock Text="No"/>
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Window.Resources>
        <Grid>
            <ToggleButton Style="{StaticResource OnOffToggleStyle}"/>
        </Grid>
    </Window>
    
    0 讨论(0)
  • 2021-02-11 05:44

    Building up on @Batuu's reply, to be just left with the content as text just update the style to

    Updated

    <Style x:Key="OnOffToggleStyle" TargetType="ToggleButton">
      <Setter Property="Content" Value="Off"/>
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type ToggleButton}">
            <ContentPresenter />
          </ControlTemplate>
        </Setter.Value>
      </Setter>
      <Style.Triggers>
          <Trigger Property="IsChecked" Value="True">
              <Setter Property="Content" Value="On">
              </Setter>
          </Trigger>
      </Style.Triggers>
    </Style>
    

    Addition here compared to original reply is

      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type ToggleButton}">
            <ContentPresenter />
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    

    You basically set the template of the button to just be the content that it holds.

    0 讨论(0)
提交回复
热议问题