Search code examples
c#wpflistviewdatatemplatelistviewitem

How can i change single Listview's item ItemTemplate?


XAML:

<DataTemplate x:key="AwesomeDataTemplate" >
  (Awesome stuff here...)
</DataTemplate>

<DataTemplate x:key="GodLikeDataTemplate" >
  (Something better here...)
</DataTemplate>

I have a Listview with some ListViewItems in it. The ListView's ItemTemplate is AwesomeDataTemplate by default. When i hover to a ListViewItem, is it possible to change the hovered ListViewItem's item template to GodLikeDataTemplate?


Solution

  • For example you can do something like that. Use trigger and change DataTemplate of ContentTemplate property.

    <Window x:Class="ListViewSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ListViewSample"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="ListViewItem">
            <Setter Property="ContentTemplate" >
                <Setter.Value>
                    <DataTemplate>
                        <TextBlock Text="{Binding}" Foreground="Blue"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="ContentTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <TextBlock Text="{Binding}" Foreground="Red"/>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <ListView>
        <ListViewItem>123</ListViewItem>
    </ListView>