先來看一張圖(網上下的圖,加了幾個字)
實在是有夠“亂”的,慢慢來理一下;
1、Template是指控件的樣式
在WPF中所有繼承自contentcontrol類的控件都含有此屬性,(繼承自FrameworkElementdl類的TextBlock等控件無)。Template用于定義控件結構(Visual Tree),和Style有點容易混淆,每個控件初始沒有Style屬性,而在WPF中所有的控件都有默認的Template。Style也做樣式解釋,但是它改變的只是控件原來的屬性,比如長寬顏色之類的,而Template可以改變控件的形狀外形,還可以根據需要往里面添加其他的控件來豐富當前的控件。Style可以用來定義一定范圍內的所有對應控件的樣式,所以平時多為兩者結合使用。
<Style x:Key="ListBoxStyle1" TargetType="ListBox">
<Setter Property="Background" Value="#FFFFFFFF"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBox">
//............相關代碼</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
?
2、ItemsPanel是指控件的子項的布局樣式,只有那些有item的控件才有此屬性,如ListBox ,Combox,TreeView,DataGrid,TabelControl等,后面的兩個也是如此。
eg:在不做設置的時候,ListBox的Item子項是縱向排列的,但是可以通過設置ItemPanell來實現橫向排列或者其他更復雜的排列方式。
<ListBox >
<ListBox.ItemsPanel>
<ItemsPanelTemplate><VirtualizingStackPanel Orientation="Horizontal"/>//橫向排列
</ItemsPanelTemplate></ListBox.ItemsPanel>
</ListBox>
3、ItemContainerStyle是控件子項的樣式,在ListBox里即ListBoxItem的Style屬性,只是在ListBox設ItemContainerStyle表示當前控件的所有子項都默認了這個style,它的格式就是對應子項控件的Style。
<ListBox ItemContainerStyle="{StaticResource ListBoxItemStyle}"> <ListBoxItem /><ListBoxItem />
</ListBox>
與
<ListBox > <ListBoxItem Style="{StaticResource ListBoxItemStyle}"/><ListBoxItem Style="{StaticResource ListBoxItemStyle}"/>
</ListBox>
等價,但是顯然前者要方便很多。
4、ItemTemplate是控件子項的樣式,說法和1里面的相同,用法和3里面的相同,即與子項的Template屬性等價,但是這個顯然也是比較方便的。