Radiobutton样式作为xaml中的切换按钮

时间:2017-09-04 21:09:59

标签: xaml radio-button togglebutton

我有2个按钮,它应该作为开关,所以我使用单选按钮。但单选按钮的样式应该看起来像切换按钮,这意味着它不应该有一个圆圈来检查。

我搜索了很长时间,没有任何有用的资源。

<Style TargetType="{x:Type RadioButton}" BasedOn="{StaticResource {x:Type ToggleButton}}">
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
        </Style> 


    <Style TargetType="{x:Type ToggleButton}">
        <Setter Property="Background" Value="{StaticResource BgColor}" />
        <Setter Property="Foreground" Value="{StaticResource FgColor}" />
        <Setter Property="BorderBrush" Value="Transparent" />
        <Setter Property="Focusable" Value="False" />
        <Setter Property="Margin" Value="0" />
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Foreground" Value="{StaticResource HoverColor}" />
            </Trigger>
            <Trigger Property="IsPressed" Value="True">
                <Setter Property="BorderBrush" Value="{StaticResource TextBlack}" />
            </Trigger>
            <Trigger Property="IsChecked" Value="True">
                <Setter Property="BorderBrush" Value="{StaticResource TextBlack}" />
                <Setter Property="Foreground" Value="{StaticResource HoverColor}" />
            </Trigger>
        </Style.Triggers>
    </Style>

但是它为圆圈(无线电属性)留下了一个黑色的空间,而在鼠标悬停时,它显示出要检查的圆圈。

任何人都可以知道实现它的最简单方法..

1 个答案:

答案 0 :(得分:1)

您真正需要做的就是为RadioButton定义样式,如下所示:

<Style TargetType="{x:Type RadioButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <ToggleButton Content="{Binding Path=(Content), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type RadioButton}}}"
                              IsChecked="{Binding Path=(IsChecked), RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type RadioButton}}}"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

这是你的核心。您可以添加需要添加的任何内容作为另一个Setters,或者在ControlTemplate中设置样式ToggleButton,使其看起来像您想要的那样。