How do I apply a style to the ListViewItems in WPF?
Asked Answered
C

3

16

First of all, I am new to WPF.


I have this style ready for my items:

    <Style x:Key="lvItemHover" TargetType="{x:Type ListViewItem}">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="true">
                <Setter Property="Foreground" Value="Black" />
            </Trigger>
        </Style.Triggers>
    </Style>

How do I give this style to the items in my ListView?

Cream answered 22/3, 2011 at 10:3 Comment(0)
S
32

Try this

     <ListView x:Name="listView">
        <ListView.ItemContainerStyle>
            <Style TargetType="{x:Type ListViewItem}">
               <Style.Triggers>
                  <Trigger Property="IsMouseOver" Value="true">
                     <Setter Property="Foreground" Value="Black" />
                  </Trigger>
               </Style.Triggers>
            </Style>
        </ListView.ItemContainerStyle>
        <ListViewItem>Item1</ListViewItem>
        <ListViewItem>Item2</ListViewItem>
        <ListViewItem>Item3</ListViewItem>
    </ListView>
Stalwart answered 22/3, 2011 at 10:6 Comment(0)
A
6

You have many options

  • Remove the x:Key="lvItemHover" from your style and it will get applied to all your ListViewItems

  • Apply the style to each ListViewItem like

    <ListViewItem Style="{StaticResource lvItemHover}">Item1</ListViewItem>

  • Put your style inside the ListView.ItemContainerStyle as in the above post

Antiserum answered 22/3, 2011 at 10:18 Comment(0)
S
6

This is the simplest way to define ListViewItem style from static resource:

    <ListView x:Name="listView" ItemContainerStyle="{StaticResource lvItemHover}">
    </ListView>
Shushubert answered 31/1, 2017 at 22:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.