2013-04-16 39 views
2

我有四个RadioButtons在网格面板,但是当我这样做:如何获得的检查单选按钮的值在WPF

<GroupBox x:Name="radioButtons"> 
    <RadioButton Content="1" Height="16" HorizontalAlignment="Left" Margin="10,45,0,0" Name="status1" VerticalAlignment="Top" /> 
    <RadioButton Content="2" Height="16" HorizontalAlignment="Left" Margin="10,67,0,0" Name="status2" VerticalAlignment="Top" /> 
    <RadioButton Content="3" Height="16" HorizontalAlignment="Left" Margin="10,89,0,0" Name="status3" VerticalAlignment="Top" /> 
    <RadioButton Content="4" Height="16" HorizontalAlignment="Left" Margin="10,111,0,0" Name="status4" VerticalAlignment="Top" /> 
</GroupBox> 

它说:

Error 1 The object 'GroupBox' already has a child and cannot add 'RadioButton'. 'GroupBox' can accept only one child.

而最后3 RadioButtons说:

The property 'Content' is set more than once.

这有什么错我的GroupBox?此外,在我的代码中,我想访问被检查的RadioButton(最好是int)。我该怎么做呢?我尝试着看Google,并且发现了很多结果,但是我无法理解其中的任何结果。

回答

2

GroupBox只能容纳1项。因此,让一个版面项目,然后把RadioButton的里面

因此,你在做是说试图设置GroupBox多次的Content属性的错误。现在可以设置Content一旦这是StackPanel和布局项目可容纳许多孩子 - >RadioButton

<GroupBox x:Name="radioButtons"> 
    <StackPanel> 
    <RadioButton Name="status1" 
        Height="16" 
        Margin="10,45,0,0" 
        HorizontalAlignment="Left" 
        VerticalAlignment="Top" 
        Content="1" /> 
    <RadioButton Name="status2" 
        Height="16" 
        Margin="10,67,0,0" 
        HorizontalAlignment="Left" 
        VerticalAlignment="Top" 
        Content="2" /> 
    <RadioButton Name="status3" 
        Height="16" 
        Margin="10,89,0,0" 
        HorizontalAlignment="Left" 
        VerticalAlignment="Top" 
        Content="3" /> 
    <RadioButton Name="status4" 
        Height="16" 
        Margin="10,111,0,0" 
        HorizontalAlignment="Left" 
        VerticalAlignment="Top" 
        Content="4" /> 
    </StackPanel> 
</GroupBox> 

关于你的第二个问题,在谷歌的WPF单选Here的第一个环节有一个体面的样本。你的意思是你不明白他们。如果你不明白什么是Binding/Converter,你可能应该先看看这些话题?

一种非常原始的方式来通知RadioButton在非MVVM方式检查:

private void RadioButtonChecked(object sender, RoutedEventArgs e) { 
    var radioButton = sender as RadioButton; 
    if (radioButton == null) 
    return; 
    int intIndex = Convert.ToInt32(radioButton.Content.ToString()); 
    MessageBox.Show(intIndex.ToString(CultureInfo.InvariantCulture)); 
} 

然后在每个XAML中你RadioButton的添加Checked="RadioButtonChecked"

+0

感谢它真的帮了我!你能指导我如何让代码签入谁? – DorZ11

+0

我添加了一个链接到我的答案的最后部分。 http://wpftutorial.net/RadioButton.html是实现你所需要的一个相当不错的样本。 – Viv

+0

添加了一个绑定到RadioButton的Checked事件中的函数。 intIndex应该是一个int值,前提是RadioButton的内容相应地设置为 – Viv

0

如果你想许多元素或控件那么你必须把它们放在布局容器中。

  • 电网
  • 的StackPanel
  • DockPanel中
  • WrapPanel
  • 等.....
相关问题