LoginSignup
2
11

More than 5 years have passed since last update.

[WPF] ItemTemplateを動的に変更する

Last updated at Posted at 2017-08-31

目的

ItemsControlでデータを表示している際に、StyleModeプロパティの値を変更することで使用しているItemTemplateを変更・反映したい。
今回は、StyleModeが1の場合は大きいフォントでName、小さいフォントでMessageを2行で表示し、StyleModeが2の場合はNameのみを小さいフォントで表示する要素を作成する。

方法

Window.Resourceに使いたいDataTemplateを登録し、それぞれをバインドしたStyleModeプロパティの値でItemTempateに割り当てるDataTriggerを作成する。

Mainpage.xaml
<Window.Resources>
    <ResourceDictionary>
        <DataTemplate x:Key="DataTemplate1" >
            <TextBlock Margin="5">
                <Run Text="{Binding Name}" FontSize="25"/>
                <LineBreak />
                <Run Text="{Binding Message}" FontSize="15"/>
            </TextBlock>
        </DataTemplate>
        <DataTemplate x:Key="DataTemplate2" >
            <TextBlock Margin="5">
                <Run Text="{Binding Name}" FontSize="15"/>
            </TextBlock>
        </DataTemplate>

        <Style x:Key="selectableContentStyle" TargetType="{x:Type ItemsControl}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding StyleMode}" Value="1">
                    <Setter Property="ItemTemplate" Value="{StaticResource DataTemplate1}" />
                </DataTrigger>
                <DataTrigger Binding="{Binding StyleMode}" Value="2">
                    <Setter Property="ItemTemplate" Value="{StaticResource DataTemplate2}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ResourceDictionary>
</Window.Resources>

そして、使用するItemsControlでStyleとして指定する。

Mainpage.xaml
<ItemsControl ItemsSource="{Binding Data}" 
              Style="{StaticResource selectableContentStyle}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Vertical" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

備考

最初、こういうことがやりたい場合はDataTemplateSelectorを使うっていう情報に当たったので頑張っていたが、なかなかうまくいかなかった。
今回の方法で実現できたものの、ひょっとすると邪道なやり方なのかもしれない。

2
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
11