在WPF中更改togglebutton的自定义行为

时间:2011-05-17 14:31:02

标签: wpf

我是WPF的新手。

改变togglebutton行为的方法是什么。 enter image description  hereenter image description here 黑色baground,没有边框。 是否需要使用控制模板?

2 个答案:

答案 0 :(得分:4)

是的,您想使用ControlTemplate来更改ToggleButton的外观。请查看ToggleButton以及本文的页面:

Customizing the Appearance of an Existing Control by Creating a ControlTemplate

让你入门。

答案 1 :(得分:4)

您必须修改“控制模板”或“样式”以更改现有可用控件的外观。看一下这个与您的要求类似的样本。我所做的是改变了Chrome(默认的窗口样式)并使用Border和内容演示者创建了我自己的风格。然后我创建了样式的触发器。对于可视化,在鼠标悬停和缺血事件中,我正在改变边框的背景颜色。

<Window.Resources>
    <Style x:Key="ToggleButtonStyle1" TargetType="{x:Type ToggleButton}">
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Padding" Value="1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ToggleButton}">
                    <Border x:Name="border">
                        <ContentPresenter 
                        SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
                        RecognizesAccessKey="True" TextElement.Foreground="White" HorizontalAlignment="Center"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsKeyboardFocused" Value="true"/>
                        <Trigger Property="IsChecked" Value="true">
                            <Setter Property="Background" TargetName="border" Value="#FF6C6C6C"/>
                            <Setter Property="CornerRadius" TargetName="border" Value="5"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" TargetName="border" Value="#FF282828"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="#ADADAD"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

<Grid x:Name="LayoutRoot">
    <ToggleButton HorizontalAlignment="Left" Margin="136,59,0,0" Style="{DynamicResource ToggleButtonStyle1}" VerticalAlignment="Top" Width="27" Height="24" Content="-" FontSize="21.333" FontWeight="Bold" HorizontalContentAlignment="Center" Padding="0" VerticalContentAlignment="Center" IsThreeState="True"/>
</Grid>