WPF if 语句基于单选按钮是否选中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15619926/
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 if statement based on radio button checked or not
提问by Nallware
I'm having difficulty with something which seems like it should be very simple. I'm coming from Windows Forms and starting up with WPF. I think I have a simple syntax issue but I can't seem to find a specific example for this radio button issue.
我在做一些看起来应该很简单的事情时遇到了困难。我来自 Windows 窗体并开始使用 WPF。我想我有一个简单的语法问题,但我似乎找不到这个单选按钮问题的具体例子。
I have a radio button on my GUI for a query to run either via a map selection or a list. When load is clicked, it should perform one operation if map is selected, a different operation for list. Code looks similar to this:
我的 GUI 上有一个单选按钮,用于通过地图选择或列表运行查询。当点击加载时,如果选择地图,它应该执行一个操作,另一个操作列表。代码看起来类似于:
private void Load_Click(object sender, RoutedEventArgs e)
{
if (rdBtnList.Checked == true)
{
//do this
}
// if rdBtnList not checked (ie if rdBtnMap is checked)
// do this
}
Any help would be greatly appreciated. Thanks.
任何帮助将不胜感激。谢谢。
回答by Federico Berasategui
Change:
改变:
if (rdBtnList.Checked == true)
to
到
if (rdBtnList.IsChecked == true)
Note:
笔记:
I'm coming from Windows Forms and starting up with WPF
I'm coming from Windows Forms and starting up with WPF
- You must forget everything you ever learned in winforms, and embrace MVVM. You should create a ViewModel and bind your
rdBtnList.IsCheckedproperty to some boolean value in the ViewModel, then perform your logic in there. The views' code behind is not the right place for application logic.
- 你必须忘记你在 winforms 中学到的一切,并拥抱 MVVM。您应该创建一个 ViewModel 并将您的
rdBtnList.IsChecked属性绑定到ViewModel中的某个布尔值,然后在那里执行您的逻辑。视图背后的代码不是应用程序逻辑的正确位置。
回答by JaredPar
The property in WPF is called IsCheckedhence you just need to update the ifstatement
WPF 中的属性被调用,IsChecked因此您只需要更新if语句
if (rdBtnList.IsChecked == true) {
...
}
The IsCheckedproperty is bool?(nullable value) in WPF so you may choose to be more explicit here by doing the following
该IsChecked属性bool?在 WPF 中为(nullable value),因此您可以通过执行以下操作选择在此处更明确
if (rdBtnList.IsChecked.HasValue && rdBtnList.IsChecked.Value) {
...
}
回答by Metro Smurf
Are you missing a return statement? As is, the posted code will always execute the if not checked path:
您是否缺少 return 语句?照原样,发布的代码将始终执行 if not checked 路径:
private void Load_Click(object sender, RoutedEventArgs e)
{
if (rdBtnList.IsChecked == true)
{
//do this
return; // return, or the if not checked path below will always win.
}
// if rdBtnList not checked (ie if rdBtnMap is checked)
// do this
}
In WPF, you'll need to use the IsChecked property. See the RadioButton Classfor more details.
在 WPF 中,您需要使用 IsChecked 属性。有关更多详细信息,请参阅RadioButton 类。

