我在网格面板中有四个RadioButtons
,但是当我这样做时:
<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>
它说:
错误1对象'GroupBox'已经有一个子节点,无法添加'RadioButton'。 'GroupBox'只能接受一个孩子。
最后三个RadioButtons
说:
属性“内容”设置不止一次。
我的GroupBox
有什么问题?此外,在我的代码中,我想访问被检查的RadioButton
(最好是int
)。我该怎么做呢?我试图查看谷歌,我发现了很多结果,但我无法理解它们中的任何一个。
GroupBox
只能容纳1个项目,因此有关尝试多次设置Content
的GroupBox
属性的错误。
因此,将其设为Layout项,然后将RadioButton
s放入其中。现在,你设置Content
一次,这是StackPanel
,而布局项目可以容纳许多孩子 - > RadioButton
s。
<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>
至于你的第二个问题,Christian Mosers WPF Tutorial.net有一个不错的样本。如果您不理解它,您可能应首先查看Binding
和Converter
主题。
以非MVVM方式检查RadioButton
的非常粗略的方式:
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
s中,添加Checked="RadioButtonChecked"
。
如果您需要许多元素或控件,则必须将它们放在布局容器中。