Search code examples
wpftemplatesitemscontrol

Use different template for last item in a WPF itemscontrol


I'm using a custom template in my itemscontrol to display the following result:

item 1, item 2, item3,

I want to change the template of the last item so the result becomes:

item 1, item2, item3

The ItemsControl:

<ItemsControl ItemsSource="{Binding Path=MyCollection}">

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" IsItemsHost="True"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
        <DataTemplate>

            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Path=Name}"/>
                <TextBlock Text=", "/>
            </StackPanel>

        </DataTemplate>
    </ItemsControl.ItemTemplate>

</ItemsControl>

Is there anyone who can give a solution for my problem? Thank you!


Solution

  • I've found the solution for my problem using only XAML. If there is anybody who needs to do the same, use this:

    <ItemsControl ItemsSource="{Binding Path=MyCollection}">
    
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" IsItemsHost="True"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    
        <ItemsControl.ItemTemplate>
            <DataTemplate>
    
                <StackPanel Orientation="Horizontal">
                    <TextBlock x:Name="comma" Text=", "/>
                    <TextBlock Text="{Binding}"/>
                </StackPanel>
    
                <DataTemplate.Triggers>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource PreviousData}}" Value="{x:Null}">
                        <Setter TargetName="comma" Property="Visibility" Value="Collapsed"/>
                    </DataTrigger>
                </DataTemplate.Triggers>
    
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    
    </ItemsControl>