views:

286

answers:

2

I want the top three items in my ListView to have special style. How can i achieve this?

I have tried this but item is always null:

                    if (tracklistQueue.Items.Count > 0) {
                         ListViewItem item = (ListViewItem)tracklistQueue.ItemContainerGenerator.ContainerFromIndex(0);
                         item.Style = (Style)FindResource("StyleName");
                    }  
A: 

Solved it. The ItemContainerGenerator had not finished generating the items.

Added this to the constructor and put the code there:

this.tracklistQueue.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);
Erik
+2  A: 

You can use AlternationIndex and AlternationCount properties.

Following example sets different background color for first three rows.

Add this style definition to your UserControl (or Window):

<Style TargetType="ListViewItem">
    <Style.Triggers>
        <Trigger Property="ItemsControl.AlternationIndex" Value="0">
            <Setter Property="Background" Value="#FFFF0000" />
        </Trigger>
        <Trigger Property="ItemsControl.AlternationIndex" Value="1">
            <Setter Property="Background" Value="#FF00FF00" />
        </Trigger>
        <Trigger Property="ItemsControl.AlternationIndex" Value="2">
            <Setter Property="Background" Value="#FF0000FF" />
        </Trigger>
    </Style.Triggers>
</Style>

Set AlternationCount of ListView to value which is greater than number of rows that ListView can actually contain:

<ListView AlternationCount="1000" />

Reference:

ItemsControl.AlternationCount Property

bniwredyc
+1 - This is the proper way of doing this, as opposed to subscribing to one of the `ItemContainerGenerator` events.
Aviad P.
I don't like this solution. Besides, i already have alteration count set to 2
Erik
@Erik, its not about liking, WPF is designed to seperate UI n Business Logic, people coming from WinForm, still like to change and manipulate UI in codebehind, but this is what WPF is built for. This is what Triggers are designed for.
Akash Kava
Yes, i know. But setting AlterationCount to 1000 seems like a work around, not a solution. And how would i do this if a already have AlterationCount set to 2?
Erik
@Erik if you use mvvm pattern you can add property to items viewmodel - this is the way that I prefer.
bniwredyc
I don't actually know what pattern i use. How would i do this?
Erik
@Erik read this: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
bniwredyc