前言:本文經過一個簡單控件的建立,來看看silverlight的模板系統到底有多麼強大(固然這只是強大之處的一點點點....)寫做本文的靈感來自於我在互聯網上閒逛,看到有朋友須要這樣的需求,同時也想經過此練習來學習silverlight,但最但願的是本文能對有須要的朋友有所幫助。html
控件需求:使用單選按鈕來顯示條目和接受選擇的列表框vim
大概樣子以下:ide

方案一:經過silverlight的元素合成思想學習
這個控件能夠由如下兩元素合成:spa
1:RadioButtoncode
2:ListBoxhtm
因而,最簡單的代碼就出來了:blog
<
ListBox
Width
="150"
Height
="60"
>
<
RadioButton
Content
="單選按鈕一"
/>
<
RadioButton
Content
="單選按鈕二"
/>
<
RadioButton
Content
="單選按鈕三"
/>
<
RadioButton
Content
="單選按鈕四"
/>
</
ListBox
>
看看效果吧:get
看起來還不錯~~那若是,咱們的需求有變化,須要默認選擇第一個單選按鈕,那繼續改改吧:it
代碼
<
ListBox
Width
="150"
Height
="60"
>
<
ListBoxItem
IsSelected
="True"
>
<
RadioButton
Content
="單選按鈕一"
/>
</
ListBoxItem
>
<
RadioButton
Content
="單選按鈕二"
/>
<
RadioButton
Content
="單選按鈕三"
/>
<
RadioButton
Content
="單選按鈕四"
/>
</
ListBox
>
結果以下:

列表項第一個是被選中了,可是單選按鈕仍舊沒有被選中,那咱們就繼續改改:
代碼
<
ListBox
Width
="150"
Height
="60"
>
<
ListBoxItem
>
<
RadioButton
Content
="單選按鈕一"
IsChecked
="True"
/>
</
ListBoxItem
>
<
RadioButton
Content
="單選按鈕二"
/>
<
RadioButton
Content
="單選按鈕三"
/>
<
RadioButton
Content
="單選按鈕四"
/>
</
ListBox
>
把第一個按鈕默認是選中的,看下結果:

默認選中是能夠了,可是,當咱們點擊第二個按鈕的時候,發現第一個按鈕仍是選中的,這個問題好解決,把單選按鈕歸爲一組就好了:
<
ListBox
Width
="150"
Height
="60"
>
<
ListBoxItem
>
<
RadioButton
Content
="單選按鈕一"
IsChecked
="True"
GroupName
="go"
/>
</
ListBoxItem
>
<
RadioButton
Content
="單選按鈕二"
GroupName
="go"
/>
<
RadioButton
Content
="單選按鈕三"
GroupName
="go"
/>
<
RadioButton
Content
="單選按鈕四"
GroupName
="go"
/>
</
ListBox
>
這樣,一個目標需求的控件也算是合成了,可是其實它算不上正真意義上的控件,當你點擊列表項的時候,單選按鈕是不會被選中的,除非你點擊列表項中的單選按鈕,這樣才能選中。其實也挺強大了,這裏是把RadionButton做爲ListBox的內容控件。那麼,接下來,讓咱們再來看看運用模板技術來更好的實現這個目標需求。
方案二:利用模板技術和綁定技術來實現
須要用到ListBox的ItemContainerStyle屬性:
獲取或設置在呈現項容器時使用的樣式。
C# |
public Style ItemContainerStyle { get; set; } |
XAML 屬性元素用法 |
<ListBox>
<ListBox.ItemContainerStyle>
inlineStyle
</ListBox.ItemContainerStyle>
</ListBox> |
而後製做ListBoxItem的模板,把它的模板內容設定爲RadionButton,而後把RadioButton的IsChecked屬性綁定到ListBoxItem的IsSelected屬性上:
代碼
<
ListBox
ScrollViewer.VerticalScrollBarVisibility
="Visible"
Width
="100"
Height
="60"
x:Name
="lb"
>
<
ListBox.ItemContainerStyle
>
<
Style
TargetType
="ListBoxItem"
>
<
Setter
Property
="Template"
>
<
Setter.Value
>
<
ControlTemplate
TargetType
="ListBoxItem"
>
<
RadioButton
IsChecked
="
{Binding Path=IsSelected,RelativeSource={RelativeSource TemplatedParent}}
"
Content
="
{TemplateBinding Property=Content}
"
/>
</
ControlTemplate
>
</
Setter.Value
>
</
Setter
>
</
Style
>
</
ListBox.ItemContainerStyle
>
<
ListBoxItem
IsSelected
="True"
>
<
TextBlock
>
單選按鈕一
</
TextBlock
>
</
ListBoxItem
>
<
TextBlock
>
單選按鈕二
</
TextBlock
>
<
TextBlock
>
單選按鈕三
</
TextBlock
>
<
TextBlock
>
單選按鈕四
</
TextBlock
>
</
ListBox
>
這樣,當你選擇列表項的時候,按鈕的選中屬性就會隨着列表項的改變而改變,而且單選按鈕也不須要分組了,由於這裏它不是列表控件的內容控件了。看下最終效果:
