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属性来设置单选框类别,分成了两组。如果没有这个属性,那么这六个单选框只能选中一个。

扫描二维码关注公众号,回复: 6077592 查看本文章

用户内容:

和复选框一样,单选框也是继承于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来放置一张图片和一段文字。这里我们用了文本块控件来控制文字的显示,还可以用其他任何形式来展示。在这里我改变了文字的颜色来匹配选择。图片通过图片控件来显示。

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

猜你喜欢

转载自www.cnblogs.com/Leozi/p/10798576.html