2
votes

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, just a piece of text that either shows as yes or no.

I'd like it as a template that I can just add as a style to all my existing Toggle controls.

I tried with Blend but I am new to templating and didn't know how to do it.

2

2 Answers

11
votes

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.

4
votes

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>