Share via


ItemsControl.ItemTemplate 屬性

定義

取得或設定用來顯示每個項目的 DataTemplate

public:
 property System::Windows::DataTemplate ^ ItemTemplate { System::Windows::DataTemplate ^ get(); void set(System::Windows::DataTemplate ^ value); };
[System.ComponentModel.Bindable(true)]
public System.Windows.DataTemplate ItemTemplate { get; set; }
[<System.ComponentModel.Bindable(true)>]
member this.ItemTemplate : System.Windows.DataTemplate with get, set
Public Property ItemTemplate As DataTemplate

屬性值

DataTemplate,其指定資料物件的視覺效果。 預設為 null

屬性

範例

下列範例示範如何建立 DataTemplate 內嵌。 DataTemplate指定每個數據項在 內顯示為三TextBlock個專案StackPanel。 在此範例中,數據對像是稱為的 Task類別。 請注意,此範本中的每個 TextBlock 元素都會系結至 類別的 Task 屬性。

<ListBox Width="400" Margin="10"
         ItemsSource="{Binding Source={StaticResource myTodoList}}">
   <ListBox.ItemTemplate>
     <DataTemplate>
       <StackPanel>
         <TextBlock Text="{Binding Path=TaskName}" />
         <TextBlock Text="{Binding Path=Description}"/>
         <TextBlock Text="{Binding Path=Priority}"/>
       </StackPanel>
     </DataTemplate>
   </ListBox.ItemTemplate>
 </ListBox>

在 resources 區段中定義 DataTemplate 更常見,因此它可以是可重複使用的物件,如下列範例所示:

<Window.Resources>
<DataTemplate x:Key="myTaskTemplate">
  <StackPanel>
    <TextBlock Text="{Binding Path=TaskName}" />
    <TextBlock Text="{Binding Path=Description}"/>
    <TextBlock Text="{Binding Path=Priority}"/>
  </StackPanel>
</DataTemplate>
</Window.Resources>

現在您可以使用 myTaskTemplate 做為資源,如下列範例所示︰

<ListBox Width="400" Margin="10"
         ItemsSource="{Binding Source={StaticResource myTodoList}}"
         ItemTemplate="{StaticResource myTaskTemplate}"/>

如需完整範例,請參閱資料範本化範例簡介

備註

您可以使用 ItemTemplate 指定資料物件的視覺效果。 ItemsControl如果您的 系結至集合物件,而且您未使用 DataTemplate提供特定的顯示指令,則每個項目產生的UI是基礎集合中每個物件的字串表示。

當您在 上ItemsControl設定 ItemTemplate 時,會產生UI,如下所示 (使用 ListBox 作為範例) :

  1. 在內容產生期間,會 ItemsPanel 起始 要求,以 ItemContainerGenerator 為每個數據項建立容器。 針對 ListBox,容器是 ListBoxItem。 產生器會回呼至 ItemsControl ,以準備容器。

  2. 準備的一部分牽涉到 將 的 ItemTemplateListBox 複製為 ContentTemplateListBoxItem

  3. 類似於所有 ContentControl 型別, ControlTemplateListBoxItem 包含 ContentPresenter。 套用範本時,它會建立 ContentPresenter ,其 ContentTemplate 系結至 ContentTemplateListBoxItem

  4. 最後,會將 ContentPresenterContentTemplate 套用至本身,並建立UI。

如果您有多個 DataTemplate 已定義,而且想要提供邏輯以程式設計方式選擇並套用 DataTemplate,請使用 ItemTemplateSelector 屬性。

提供 ItemsControl 視覺自定義的絕佳彈性,並提供許多樣式和範本化屬性。 ItemContainerStyle使用屬性或 ItemContainerStyleSelector 屬性來設定樣式,以影響包含數據項的項目外觀。 例如,針對 ListBox,產生的容器是 ListBoxItem 控件;如果是 ComboBox,則為 ComboBoxItem 控件。 若要影響專案的版面配置,請使用 ItemsPanel 屬性。 如果您在控件上使用群組,則可以使用 GroupStyleGroupStyleSelector 屬性。

如需詳細資訊,請參閱 數據範本化概觀

XAML Attribute Usage

<object ItemTemplate=" ResourceExtension TemplateResourceKey"/>

XAML 值

ResourceExtension 下列其中一項: StaticResource 標記延伸DynamicResource 標記延伸。 除非樣式本身包含可能運行時間參考的參考,例如系統資源或使用者喜好設定,否則通常建議使用樣式的 StaticResource 標記延伸 參考來達到效能。

TemplateResourceKeyx:Key 指示詞 字串值,參考要要求做為資源的範本。

相依性屬性資訊

標識元欄位 ItemTemplateProperty
設定為的元數據屬性 true

適用於

另請參閱