是/否 ToggleButton 的 WPF 模板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15309812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF template for yes/no ToggleButton
提问by Paul
Can anyone help me with a simple template to make a WPF ToggleButton show "yes" or "no" depending on it's toggle state?
任何人都可以帮助我使用一个简单的模板来使 WPF ToggleButton 显示“是”或“否”,具体取决于它的切换状态?
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.
我想要它作为一个模板,我可以将它作为样式添加到我所有现有的 Toggle 控件中。
I tried with Blend but I am new to templating and didn't know how to do it.
我尝试过 Blend,但我是模板的新手,不知道该怎么做。
回答by Viv
Building up on @Batuu's reply, to be just left with the content as text just update the style to
以@Batuu 的回复为基础,只留下内容作为文本,只需将样式更新为
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.
您基本上将按钮的模板设置为它包含的内容。
回答by Batuu
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>

