1

In a custom list view, each row is composed of an image and of a text. Every even row, the image should be on the left and every odd row, it should be on the right.

Being a beginner at WPF, I wonder what is the easiest way to achieve that and to reused most of the XAML written.

The odd/even item templates really only differ by the fact that the image is on one side or the other of the text.

Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124

1 Answers1

2

I believe that you can use a trigger in the style to achieve this. You can place your image left aligned and in the trigger change that to right.

Something similar to:

<Style.Triggers>
    <Trigger Property="ItemsControl.AlternationIndex" Value="1">
           <!-- Change image position here -->
    </Trigger>
<Style.Triggers>

More information about how to use AlternationIndex here.

Edit - Working Sample

    <Style TargetType="ListViewItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListViewItem}">
                        <DockPanel>
                            <Image Source="/WpfApplication;component/Images/TestImage.jpg" DockPanel.Dock="Left" x:Name="rowImage"/>
                            <TextBlock Text="Testing..." Background="{TemplateBinding Background}"/>
                        </DockPanel>
                    <ControlTemplate.Triggers>
                        <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                            <Setter Property="DockPanel.Dock" TargetName="rowImage" Value="Right" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
Community
  • 1
  • 1
Adrian Fâciu
  • 12,414
  • 3
  • 53
  • 68
  • I know about alternation index, however I don't actually know how to use that in a real world example (again, I am rather new to WPF and XAML). I have seen examples about how to change the ListViewItem background, but I struggle to understand how to get the template to change as well. – Vincent Mimoun-Prat Oct 05 '11 at 12:27
  • @MarvinLabs, I'm not sure what you have in there exactly but I've added a working sample of what i had in mind. – Adrian Fâciu Oct 05 '11 at 13:30