WPF: How to make a “pushlike” checkbox?

旧城冷巷雨未停 提交于 2019-12-06 21:33:39

问题


I would like to make a CheckBox that looks exactly like a button. My initial feeble attempt doesn't work at all.

<CheckBox x:Name="test">
    Testing!
    <CheckBox.Template>
        <ControlTemplate>
            <Button>
                <ContentPresenter/>
            </Button>
        </ControlTemplate>
    </CheckBox.Template>
</CheckBox>

The ContentPresenter isn't working (the button is empty) and when the button is clicked, the IsChecked property does not toggle. Also, I don't know how to make the button look pushed when IsChecked is true.


回答1:


Would a ToggleButton suit your needs? CheckBox derives from it, and so they are very similar.




回答2:


I've just started to write same comment :)

<ToggleButton Name="tb"  Height="45" Width="45">
        <ToggleButton.Style>
            <Style TargetType="{x:Type ToggleButton}">
                <Setter Property="Content" Value="False"/>
                <Style.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter Property="Content" Value="True"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ToggleButton.Style>
    </ToggleButton>

And now as you wanted, Checkbox control:

<CheckBox>
        <CheckBox.Template>
            <ControlTemplate TargetType="CheckBox">
                <ToggleButton x:Name="toggleButton">
                </ToggleButton>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsChecked" Value="True" SourceName="toggleButton">
                        <Setter Property="Content" Value="True"/>
                    </Trigger>
                    <Trigger Property="Content" Value="True">
                        <Setter Property="IsChecked" Value="True"/>
                    </Trigger>
                </ControlTemplate.Triggers>
             </ControlTemplate>
        </CheckBox.Template>
    </CheckBox>



回答3:


I agree that ToggleButton is the way to go, but if you want your content to show up in your example, try changing your ContentPresenter declaration to this:

<ContentPresenter Content="{TemplateBinding Content}" />


来源:https://stackoverflow.com/questions/1013779/wpf-how-to-make-a-pushlike-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!