Click here to Skip to main content
Click here to Skip to main content
Technical Blog

WPF ItemsControl with alternating items and hover effect

, 25 Apr 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
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 detail 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 a 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.

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; }
    }
}

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 can not 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.

<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 done 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.

<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)

Share

About the Author

Rahman Masudur
Software Developer (Senior) Satori Tech Solutions, Inc.
Australia Australia
About Md. Masudur Rahman
 
Masudur currently works at Satori Tech Solutions, Inc. 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

 
GeneralMy vote of 5 Pinmemberifink27-Feb-13 2:17 
QuestionAlternating Groups PinmemberMST_stu21-Oct-11 3:26 
Generalnice..... PinmemberPritesh Aryan27-May-11 0:44 
Generalsuper Pinmemberjkristia20-Jan-10 3:41 
GeneralRe: super PinmemberR. M. Masudur20-Jan-10 17:54 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.141022.2 | Last Updated 25 Apr 2009
Article Copyright 2009 by Rahman Masudur
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid