wpf 如何在WPF中一次只选择一个复选框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16810994/
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
How to select only one checkbox at a time in WPF?
提问by Siva Charan
I have to keep 2 checkboxes and only one should be selected at a time. But in my following code both are getting selected. How should I achieve my functionality in WPF?
我必须保留 2 个复选框,并且一次只能选择一个。但是在我下面的代码中,两者都被选中了。我应该如何在 WPF 中实现我的功能?
<StackPanel Orientation="Vertical" Name="spRoles">
<CheckBox Name="chkMale" Content="Male" />
<CheckBox Name="chkFemale" Content="Female" />
</StackPanel>
I have to use checkboxes only not radio buttons.
我必须只使用复选框而不是单选按钮。
回答by Fabio Marcolini
listen for the select event or something similar and check the other checkbox
侦听 select 事件或类似事件,然后选中其他复选框
public void MaleOnSelection(object sender, EventArgs e)
{
if(chkFemale.Selected)
chkFemale.Selected=false;
}
clearly you have to do the same for the female checkbox
显然你必须对女性复选框做同样的事情
anyway as stated by other a radio button would be better, you can style it as a checkbox if that's what you need
无论如何,其他单选按钮会更好,如果这是您需要的,您可以将其设置为复选框
回答by Siva Charan
In your case, you should use Radio buttons.
在您的情况下,您应该使用单选按钮。
Allowing checkboxes to select only one, it doesn't make sense.
允许复选框只选择一个,这是没有意义的。
If you still use checkboxes then whole concept of checkboxes will go off.
如果您仍然使用复选框,那么复选框的整个概念就会消失。
回答by Ganapathy
In this case just use a radio button instead of Check box. Check boxes are mostly used for multiple item selection.
在这种情况下,只需使用单选按钮而不是复选框。复选框主要用于多项目选择。
回答by RWo
For those who have the vision of purpose and disagree that allowing checkboxes to select only one does not make sense. You can call the method for every checkbox in the group.
对于那些有目标但不同意允许复选框仅选择一个是没有意义的人。您可以为组中的每个复选框调用该方法。
private void uncheckCheckBoxes(object sender)
{
if (radioButtonEdit.IsChecked == true)
{
CheckBox currentcheckbox = (CheckBox)sender;
foreach (var checkBox in ManyCheckBoxes.Children.OfType<CheckBox>().Where(cb => (bool)cb.IsChecked))
{
if (!currentcheckbox.Name.Equals(checkBox.Name))
{
checkBox.IsChecked = false;
}
}
}
}
private void checkbox1_Checked(object sender, RoutedEventArgs e)
{
uncheckCheckBoxes(sender);
}

