WPF中单选框RadioButton

单选框RadioButton的基本使用:

<StackPanel Margin="10">
           <Label FontWeight="Bold">Are you ready?</Label>
           <RadioButton>Yes</RadioButton>
           <RadioButton>No</RadioButton>
           <RadioButton IsChecked="True">Maybe</RadioButton>
</StackPanel>

如图:

 

其中Radio Button中的IsChecked属性为True时,时设置默认选中,用户点击另外两个中的一个就可以改变这个属性。这个属性也用在后台代码中,来检查一个单选框是否被选中。

单选框组的用法:

运行上面的例子,你会发现只能有一个单选框被选中。那么,如果你同时有好几组单选框,每组都有其自己的选项,如何来选呢?GroupName属性正是用在这种情况下,蕴蓄你哪几个单选框是一起的。

<StackPanel Margin="10">
                <Label FontWeight="Bold">Are you ready?</Label>
                <RadioButton GroupName="ready">Yes</RadioButton>
                <RadioButton GroupName="ready">No</RadioButton>
                <RadioButton GroupName="ready" IsChecked="True">Maybe</RadioButton>
 
                <Label FontWeight="Bold">Male or female?</Label>
                <RadioButton GroupName="sex">Male</RadioButton>
                <RadioButton GroupName="sex">Female</RadioButton>
                <RadioButton GroupName="sex" IsChecked="True">Not sure</RadioButton>
</StackPanel>

如图:

 

使用GroupName属性来设置单选框类别,分成了两组。如果没有这个属性,那么这六个单选框只能选中一个。

用户内容:

和复选框一样,单选框也是继承于ContentControl基类,能够放置用户内容并在旁边显示。如果你只是定义了一串文字,那么WPF会自动生成一个文本块来显示它们。除了文字,你还可以放置各种控件到里面,如下面的例子:

Xaml:

<StackPanel Margin="10">
            <Label FontWeight="Bold">Are you ready?</Label>
            <RadioButton>
                <WrapPanel>
                    <Image Width="16" Height="16" Margin="0,0,5,0" Source="Resources/timg (8).jpg" />
                    <TextBlock Text="Yes" Foreground="Green" />
                </WrapPanel>
            </RadioButton>
            <RadioButton Margin="0,5">
                <WrapPanel>
                    <Image  Width="16" Height="16" Margin="0,0,5,0" Source="Resources/timg (8).jpg"  />
                    <TextBlock Text="No" Foreground="Red" />
                </WrapPanel>
            </RadioButton>
            <RadioButton IsChecked="True">
                <WrapPanel>
                    <Image  Width="16" Height="16" Margin="0,0,5,0" Source="Resources/timg (8).jpg" />
                    <TextBlock Text="Maybe" Foreground="Gray" />
                </WrapPanel>
            </RadioButton>
</StackPanel>

如图:

标记很好用,上面的例子看起来很繁琐,但是要表达的概念很简单。每个单选框我们都使用一个WrapPanel来放置一张图片和一段文字。这里我们用了文本块控件来控制文字的显示,还可以用其他任何形式来展示。在这里我改变了文字的颜色来匹配选择。图片通过图片控件来显示。

注意你只要点击单选框的任何地方,不管是图片还是文字,都可以选中它。这是因为图片和文字都是单选框的内容。如果你在单选框旁边放置一个单独的容器,用户就必须去点击单选框中的小圆圈才能生效,这是非常不切实际。

 

转载于:https://www.cnblogs.com/Leozi/p/10798576.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值