WPF之RadioButton单选框和checkbox多选框

发布于:2024-04-26 ⋅ 阅读:(22) ⋅ 点赞:(0)

RadioButton 单选框: 实现分组的单选框,

checkbox 多选框: 表示用户可以选择和清除的控件。

常用属性

GroupName 

获取或设置指定哪些 RadioButton 控件互相排斥的名称
Content 内容
IsChecked 是否选中

常用事件

checked   选中的事件
unchecked   未选中的事件

RadioButton实例

标签布局
<Grid Name="g1">
    <RadioButton  GroupName="sex" 
                  Content="男" 
                  FontSize="20" >
    </RadioButton>
    <RadioButton  GroupName="sex"
                  Content="女"
                  FontSize="20">
    </RadioButton>
</Grid>


后台CS代码
private void Button_Click(object sender, RoutedEventArgs e)
{
    // 点击获取选中的单选的内容
    string s = "";
    foreach (var child in g1.Children)
    {
        if (child is RadioButton && ((RadioButton)child).IsChecked == true)
        {
            s += ((RadioButton)child).Content;
        }
    }
    MessageBox.Show(s);
}

Checkbox多选框实例

标签布局
<Grid Name="grid">
    <Label Width="400" Height="40" Background="Pink" FontSize="20" Content="我的爱好:" VerticalAlignment="Top" Name="l1"></Label>
    <CheckBox Content="看美女" HorizontalAlignment="Center" VerticalAlignment="Top"
              Margin="0,100" Width="200" Height="40" FontSize="20"
              VerticalContentAlignment="Center" Name="one" Unchecked="three_Checked" Checked="CheckBox_Checked"></CheckBox>
    <CheckBox Content="玩游戏" HorizontalAlignment="Center" VerticalAlignment="Top"
      Margin="0,150" Width="200" Height="40" FontSize="20"
      VerticalContentAlignment="Center" Name="two" Unchecked="three_Checked" Checked="CheckBox_Checked"></CheckBox>
    <CheckBox Content="听音乐" HorizontalAlignment="Center" VerticalAlignment="Top"
      Margin="0,200,0,0" Width="200" Height="40" FontSize="20"
      VerticalContentAlignment="Center" Name="three" Unchecked="three_Checked" Checked="CheckBox_Checked"></CheckBox>
    <Button Content="获取爱好" HorizontalAlignment="Center" VerticalAlignment="Top"
            Width="200" Height="40" FontSize="30" Margin="0,270,0,0" Click="Button_Click"></Button>
    <CheckBox Content="全选" HorizontalAlignment="Left" VerticalAlignment="Top" 
        Margin="300,60,0,0" Width="125" Height="40" FontSize="15"
        VerticalContentAlignment="Center" Checked="CheckBox_Checked" Name="quanx" Unchecked="three_Checked" Click="CheckBox_Click" Tag="2"/>
</Grid>



CS后台代码
private void Button_Click(object sender, RoutedEventArgs e)
{
    // 获取所有的checkbox 再根据checkbox的属性ischeck是否为true,如果为true证明选中需要获取文本

    // 1 获取当前窗口grid下所有控件
    UIElementCollection c1 = grid.Children;

    // 2 遍历c1下所有的控件
    // UIElement 控件的类
    string s = "";
    foreach (UIElement element in c1)
    {
        // 3 判断element是不是多选框并且多选
        if (element is CheckBox && ((CheckBox)element).IsChecked == true)
        {
            s += ((CheckBox)element).Content;
        }
    }
    MessageBox.Show(s);
}