WPF 切换按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21224824/
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 togglebutton
提问by Ross
I've got an issue with a custom WPF button - whenever I click on it, it receives a click event but does not seem to get toggled (does not stay down when I click on another button). I've tried everything I can think of and still can't get it to work.
我有一个自定义 WPF 按钮的问题 - 每当我点击它时,它都会收到一个点击事件,但似乎没有被切换(当我点击另一个按钮时不会保持关闭)。我已经尝试了所有我能想到的方法,但仍然无法让它工作。
One weird thing that I have noticed though is that when I put a breakpoint in the MouseDown handler and just hit F5 to continue at that point, the button gets toggled and stays down. This leads me to believe that this is some sort of focus issue?
不过,我注意到的一件奇怪的事情是,当我在 MouseDown 处理程序中放置一个断点并在那时按 F5 继续时,按钮会被切换并保持按下状态。这让我相信这是某种焦点问题?
<ToggleButton Name="ToggleButton" PreviewMouseDown="ToggleButton_MouseDown_1" IsThreeState="False">
<StackPanel Orientation="Vertical">
<Label Content="Single" FontSize="15" FontWeight="Medium"/>
<Label Content="Speaker"/>
</StackPanel>
</ToggleButton>
private void ToggleButton_MouseDown_1(object sender, MouseButtonEventArgs e)
{
ToggleButton.IsChecked = !ToggleButton.IsChecked;
}
private void ToggleButton_MouseDown_1(object sender, MouseButtonEventArgs e)
{
ToggleButton.IsChecked = !ToggleButton.IsChecked;
}
Help? :)
帮助?:)
回答by Iain
As @Nick said in his comment, just remove your event handler PreviewMouseDown="ToggleButton_MouseDown_1"completely and it should work just fine.
正如@Nick 在他的评论中所说,只需PreviewMouseDown="ToggleButton_MouseDown_1"完全删除您的事件处理程序,它应该可以正常工作。
If this is not the case you must have some other code which is causing the issue.
如果不是这种情况,您必须有其他一些导致问题的代码。
回答by bwall
It sounds like you want the functionality of a set of radio buttons, but the look of a bunch of toggle buttons. In cases like these, using the inherited Control.Template property is really handy:
听起来您想要一组单选按钮的功能,但想要一堆切换按钮的外观。在这种情况下,使用继承的 Control.Template 属性非常方便:
In your page resources, you can add:
在您的页面资源中,您可以添加:
<Style TargetType="RadioButton">
<Setter Property="Template">
<Setter.Value>
<ContentTemplate>
<ToggleButton Content="{TemplateBinding Content}" IsChecked="{TemplateBinding IsChecked}"/>
</ContentTemplate>
</Setter.Value>
</Setter>
</Style>
And then in your code:
然后在你的代码中:
<RadioButton Content="MyContent" GroupName="MyGroup"/>
This should make an object that looks like a toggle button, but deselects when you select something from the same group, like a RadioButton. You can further modify the ToggleButton in the Template until you get the look that you want.
这应该使一个对象看起来像一个切换按钮,但是当您从同一组中选择某些内容时会取消选择,例如 RadioButton。您可以进一步修改模板中的 ToggleButton,直到获得所需的外观。

