WPFのControlTemplateとDataTemplateの備忘録
データを表現するコントロール2種
ContentControl
: 単一の内容(Content)を表現するコントロール。(例)Button
Label
TabItem
etc.ItemsControl
:コレクション(Items、ItemsSource)を表現するコントロール。(例)ListBox
コントロール自体(表現する内容(ContentやItems)の外側)の見た目を自作したい場合
Control.Template
に自作したControlTemplate
をセットする。
ContentControl
のContent(つまりContentPresenter
の内側)の見た目を自作したい場合
ContentControl.ContentTemplate
に自作したDataTemplate
をセットする。
ItemsControl
のItems(つまりIsItemsHost=True
であるパネルの内側)の各要素の見た目を自作したい場合
ItemsControl.ItemTemplate
に自作したDataTemplate
をセットする。これはListBox
に対するListBoxItem
のような子要素のContentTemplate
にセットするのと同じ。- 複数の
DataTemplate
を使い分けたいならItemTemplateSelector
を使う。
自作とまでは言わずスタイルを適用したいだけの場合
- コントロール自体(表現する内容(ContentやItems)の外側)なら普通に
Style
にセットする。 ItemsControl
のItems1つ1つに適用する場合はItemsControl.ItemsContainerStyle
にセットする。- 複数のスタイルを使い分けたいなら
ItemsControl.ItemsContainerStyleSelector
を使う。
ちゃんとリファレンスに目を通す
Control.Template Property (System.Windows.Controls) | Microsoft Docs DataTemplate Class (System.Windows) | Microsoft Docs ControlTemplate Class (System.Windows.Controls) | Microsoft Docs ContentControl.ContentTemplate Property (System.Windows.Controls) | Microsoft Docs ItemsControl.ItemTemplate Property (System.Windows.Controls) | Microsoft Docs