Click here to Skip to main content
15,867,686 members
Articles / Desktop Programming / WPF

WPF ItemsControl with Alternating Items and Hover Effect

Rate me:
Please Sign up or sign in to vote.
4.95/5 (11 votes)
25 Apr 2009CPOL3 min read 123.4K   28   6
Shows how to use the WPF ItemsControl with alternating items and hover effect

Introduction

In this short article, we are going to see a few tricks about WPF ItemsControl. ItemsControl is one of the simplest yet powerful controls in WPF. ItemsControl is just like the Repeater control in ASP.NET. It supports Binding and supports custom templates to display data. For a detailed study about the power of ItemsControl, please read the MSDN documentation here. In this article, we are going to focus on how to display the alternating items in an ItemsControl and apply a few effects on the items of an ItemsControl.

ItemsControlAlternatingItem

Use Alternating Item Style

ItemsControl can be used to display data both via populating the ItemsControl.Items collection or by specifying an ItemsSource in the ItemControl.ItemsSource property. In this example, we are going to use an ItemsSource to display our data. Let's assume we have a custom class called Country and we want to display the information about Country in an ItemsControl. Shown below is a simple code listing to get the total idea.

C#
public partial class Window1 : Window
{
    public Window1()
    {
        loadDemoData();
        this.DataContext = this;
    }

    public static readonly DependencyProperty DataListProperty = 
        DependencyProperty.Register(
        "DataList", typeof(ObservableCollection<country>), typeof(Window1));
    
    private void loadDemoData()
    {
        ObservableCollection<country> data = new ObservableCollection<country>();
        Country c1 = new Country { ID = "1", Name = "Bangladesh", 
            Capital = "Dhaka", Continent = "Asia" };
        Country c2 = new Country { ID = "2", Name = "India", 
            Capital = "Delhi", Continent = "Asia" };
        Country c3 = new Country { ID = "3", Name = "U.S.A", 
            Capital = "Washington", Continent = "North America" };
        Country c4 = new Country { ID = "4", Name = "Australia", 
            Capital = "Canbarra", Continent = "Australia" };
        Country c5 = new Country { ID = "5", Name = "Kenya", 
            Capital = "", Continent = "Africa" };
        data.Add(c1);
        data.Add(c2);
        data.Add(c3);
        data.Add(c4);
        data.Add(c5);
        this.SetValue(Window1.DataListProperty, data);
    }

    public class Country
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string Continent { get; set; }
        public string Capital { set; get; }
    }
}</country></country></country>

In a few examples available in the online community, I have seen that ItemsControl is not directly used to display the idea of alternating items, rather a list box, or perhaps a more higher level control is shown to display alternating items. In this section, we will see how we can add styles in the items and alternating items of an ItemsControl just by using a simple DataTemplate. When we use the ItemsControl, the items of ItemsControl are generally rendered inside a ContentPresenter, which has only a few basic properties, and we cannot assign the background or foreground.

Using a DataTemplate and the smart use of styles on a DataTemplate might just solve our problem. Below is a complete code listing of how to do the intended effect.

XML
<Window x:Class="WPFDemo.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ItemsControl" MinHeight="350" 
        MinWidth="550" Background="#f5f5f5">
    <Window.Resources>
        <Style x:Key="alternatingWithTriggers" 
               TargetType="{x:Type ContentPresenter}">
            <Setter Property="Height" Value="25"></Setter>
        </Style>
        <DataTemplate x:Key="MyItemTemplate">
            <Border x:Name="yahoo">
                <StackPanel Orientation="Horizontal">
                    <Label Content="{Binding Name}"></Label>
                    <Label Content="is in"></Label>
                    <Label Content="{Binding Continent}"></Label>
                </StackPanel>
            </Border>
            <DataTemplate.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                    <Setter Property="Background" Value="#e9e9e9" 
                            TargetName="yahoo"></Setter>
                </Trigger>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="#d9d9d9" 
                            TargetName="yahoo"></Setter>
                </Trigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </Window.Resources>
    <Grid MinHeight="350" MinWidth="550">
        <ItemsControl ItemsSource="{Binding DataList}" 
            ItemContainerStyle="{StaticResource alternatingWithTriggers}" 
            AlternationCount="2" 
            ItemTemplate="{StaticResource MyItemTemplate}"/>
    </Grid>
</Window>

In the above code listing, we have not made any style changes in the item container styles; rather, we override the item template and use the item templates style in such a way that it shows the alternate items style. The main engine to do this trick is the AlternatingItemIndex property of ItemsControl. In the data template, we used a trigger to check the index of the item and then apply the style to the DataTemplates of one of the inner elements.

Hover Effect

Applying a hover effect is now easy since we know how to apply styles using a trigger. But, in this case, we won't use AlternatingItemIndex. We want to apply a mouse over effect regardless of whether it is an item or alternating item. Below is a code snippet showing the hover effect on items.

XML
<Style x:Key="onmouseover" TargetType="{x:Type StackPanel}"> 
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="Yellow">
            </Setter>
        </Trigger>
    </Style.Triggers>
</Style>
<DataTemplate x:Key="MyItemTemplate">
    <Border x:Name="yahoo">
        <StackPanel Orientation="Horizontal" 
                    Style="{StaticResource onmouseover}">
            <Label Content="{Binding Name}"></Label>
            <Label Content="is in"></Label>
            <Label Content="{Binding Continent}"></Label>
        </StackPanel>
    </Border>
    <DataTemplate.Triggers>
        <Trigger Property="ItemsControl.AlternationIndex" Value="0">
            <Setter Property="Background" Value="#e9e9e9" 
                    TargetName="yahoo"></Setter>
        </Trigger>
        <Trigger Property="ItemsControl.AlternationIndex" Value="1">
            <Setter Property="Background" Value="#d9d9d9" 
                    TargetName="yahoo"></Setter>
        </Trigger>
    </DataTemplate.Triggers>
</DataTemplate>

In the above code snippet, you can see that we have applied the style on a StackPanel. The style of hover on border on the parent control of the data template will not work, since we have already added styles using a trigger in the data template. So, we define a separate style for the StackPanel and apply to it. And, that concludes our mission.

Summary

In this short article, we saw how we can display alternating items using the ItemsControl. In this demonstration, we used AlternatingItemCount as 2; we can set it to greater than two, but to get the alternating item effect, it must be larger than 1. The styles must be modified to support AlternatingItemCount. For more details on ItemsControl, please visit the links in the References section below.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Riteq
Australia Australia
About Md. Masudur Rahman

Masudur currently works at Riteq as a software developer. Masudur Lives in Sydney, Australia.

Awards

26 May 2009: Monthly competition: Best ASP.NET article of April 2009

24 Mar 2009: Monthly competition: Best ASP.NET article of February 2009

Masudur Blog

Masudur put down his interesting learning experiences in his blog at http://munnaondotnet.blogspot.com/.

Comments and Discussions

 
PraiseThank you Pin
Gail Bowen1-Mar-20 7:00
Gail Bowen1-Mar-20 7:00 
GeneralMy vote of 5 Pin
ifink27-Feb-13 2:17
ifink27-Feb-13 2:17 
it helps me wonderfull
QuestionAlternating Groups Pin
MST_stu21-Oct-11 3:26
MST_stu21-Oct-11 3:26 
Generalnice..... Pin
Pritesh Aryan27-May-11 0:44
Pritesh Aryan27-May-11 0:44 
Generalsuper Pin
jkristia20-Jan-10 3:41
jkristia20-Jan-10 3:41 
GeneralRe: super Pin
Rahman Masudur20-Jan-10 17:54
Rahman Masudur20-Jan-10 17:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.