XAML 模板
介紹兩種常用的模板: DataTemplate 和 ControlTemplate
1. DataTemplate
將 ItemsControl 控件綁定到數據集合時,或是在多個ContentControl 控件之間分享 UIElement 時,常使用到DataTemplate 來定義數據。
DataTemplate 的定義格式
<DataTemplate …>
templateContent
</DataTemplate …>
templateContent 表示定義的DataTemplate 的對象樹
有一個Student對象,包含屬性StudentName和StudentNumber。
在一個頁面中添加一個 ListBox ,Binding 到這集合中要讓每個列表項對到Student對象
方法是把ItemTemplate設為數據模板,並把TextBlock的Text屬性Binding 到Student的屬性上
範例如下:
<ListBox Width="500" Margin="15" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=StudentName}"></TextBlock>
<TextBlock Text="{Binding Path=StudentNumber}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
每一個列表項對應一個學生,內容就是學生的資料,有姓名和學號。
在上例中,DataTemplate定義在ListBox控制項裡
為了讓更多的控制項共享數據模板,那可將數據模板定義成資源
然後在用ItemTemplate或ContentTemplate來引用資源
2. ControlTemplate
XAML的控制項提供的屬性不能覆蓋控制項外觀的介面
因此在設計界面的時候常需要自己定義控制項的外觀,就是定義控制項的模板
在實際開發的時候,能將ControlTemplate定義在控制項的裡面,也能定義成資源,在用Template來引用資源
示範一:
<Button> <Button.Template> <ControlTemplate TargetType="Button"></ControlTemplate> </Button.Template> </Button>
用按鈕示範怎麼使用屬性元素來設定Template,並定義ControlTemplate
示範二:
<Page>
<Page.Resources>
<ControlTemplate TargetType="TextBox" x:Key="txtboxTemplate "></ControlTemplate>
</Page.Resources>
<TextBox Name="txtboxTemplate" Text="示範二" Template="{StaticResource txtboxTemplate}"></TextBox>
</Page>
示範將ControlTemplate 定義成資源,把值引用給Template的屬性
示範三:
<StackPanel>
<StackPanel.Resources>
<Style TargetType="ComboBox" x:Key="CmbStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBox"></ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</StackPanel.Resources>
<ComboBox Style="{StaticResource CmbStyle}"></ComboBox>
</StackPanel>
示範用Style賴設置控制項的Template屬性和定義ControlTemplate