<GroupBox x:Name="groupBox" Header="Operating System" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="74" Width="280">
<StackPanel>
<RadioButton GroupName="Os" Content="Windows 7 (64-bit)" IsChecked="True"/>
<RadioButton GroupName="Os" Content="Windows 7 (32-bit)" />
</StackPanel>
</GroupBox>
我的应用程序中有几个单选按钮组
如何使用C#访问Code-Behind中检查过哪一个?
是否绝对有必要在每个RadioButton上使用 x:Name = ,还是有更好的方法?
代码示例总是受到赞赏
答案 0 :(得分:5)
是的!有一种更好的方法,称为绑定。在绑定之外,你几乎陷入困境(我可以想象分别处理所有已检查的事件,并分配给枚举,但真的更好吗?)
对于单选按钮,通常使用enum
来表示所有可能的值:
public enum OsTypes
{
Windows7_32,
Windows7_64
}
然后将每个单选按钮绑定到VM上的全局“selected”属性。您需要ValueEqualsConverter
:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.Equals(parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ((bool)value) ? parameter : Binding.DoNothing;
}
然后你的单选按钮看起来像:
<RadioButton Content="Windows 7 32-bit"
IsChecked= "{Binding CurrentOs,
Converter={StaticResource ValueEqualsConverter},
ConverterParameter={x:Static local:OsTypes.Windows7_32}}"
当然,您的VM中有一个属性:
public OsTypes CurrentOs {get; set;}
否x:名称,复杂的switch语句或其他任何内容。漂亮,干净,设计精良。 MVVM 与WPF一起工作,使用它!