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來放置一張圖片和一段文字。這里我們用了文本塊控件來控制文字的顯示,還可以用其他任何形式來展示。在這里我改變了文字的顏色來匹配選擇。圖片通過圖片控件來顯示。

注意你只要點擊單選框的任何地方,不管是圖片還是文字,都可以選中它。這是因為圖片和文字都是單選框的內容。如果你在單選框旁邊放置一個單獨的容器,用戶就必須去點擊單選框中的小圓圈才能生效,這是非常不切實際。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM