ListViewExtensions

The ListViewExtensions class provide a lightweight way to extend every control that inherits the ListViewBase class with attached properties. This means that all the extensions in this class can apply to both ListView, GridView and other controls.

ListViewBase Extensions

AlternateColor

The AlternateColor property provides a way to assign a background color to every other item.

Warning

The ContainerContentChanging event used for this extension to work, will not be raised when the ItemsPanel is replaced with another type of panel than ItemsStackPanel or ItemsWrapGrid.

Here is how this property can be used in XAML:

<Page ...
     xmlns:ui="using:CommunityToolkit.WinUI">

<ListView
    ui:ListViewExtensions.AlternateColor="Silver"
    ItemsSource="{x:Bind MainViewModel.Items, Mode=OneWay}" />

AlternateItemTemplate

The AlternateItemTemplate property provides a way to assign an alternate DataTemplate to every other item. It is also possible to combine with the AlternateColor property.

Warning

The ContainerContentChanging event used for this extension to work, will not be raised when the ItemsPanel is replaced with another type of panel than ItemsStackPanel or ItemsWrapGrid.

Here is how this property can be used in XAML:

<Page ...
     xmlns:ui="using:CommunityToolkit.WinUI">

<Page.Resources>
    <DataTemplate x:Name="NormalTemplate">
        <TextBlock Text="{Binding " Foreground="Green"></TextBlock>
    </DataTemplate>
    
    <DataTemplate x:Name="AlternateTemplate">
        <TextBlock Text="{Binding}" Foreground="Orange"></TextBlock>
    </DataTemplate>
</Page.Resources>

<ListView
    ItemTemplate="{StaticResource NormalTemplate}"
    ui:ListViewExtensions.AlternateItemTemplate="{StaticResource AlternateTemplate}"
    ItemsSource="{x:Bind MainViewModel.Items, Mode=OneWay}" />

Command

ListViewExtensions provides extension method that allow attaching an ICommand to handle ListViewBase item interaction by means of ItemClick event.

Important

ListViewBase IsItemClickEnabled must be set to true.

Here is how this property can be used in XAML:

<Page ...
     xmlns:ui="using:CommunityToolkit.WinUI">
     
<ListView
    ui:ListViewExtensions.Command="{x:Bind MainViewModel.ItemSelectedCommand, Mode=OneWay}"
    IsItemClickEnabled="True"
    ItemsSource="{x:Bind MainViewModel.Items, Mode=OneWay}"
    SelectionMode="None" />

StretchItemContainerDirection

The ItemContainerStretchDirection property provides a way to stretch the ItemContainer in horizontal, vertical or both ways. The allowed values are items from the ItemContainerStretchDirection type.

Warning

The ContainerContentChanging event used for this extension to work, will not be raised when the ItemsPanel is replaced with another type of panel than ItemsStackPanel or ItemsWrapGrid.

Here is how this property can be used from XAML:

<Page ...
     xmlns:ui="using:CommunityToolkit.WinUI">

<ListView
    ui:ListViewExtensions.StretchItemContainerDirection="Horizontal"
    ItemsSource="{x:Bind MainViewModel.Items, Mode=OneWay}" />

SmoothScrollIntoView

Use SmoothScrollIntoView helps to scroll the item into the view with animation. Specify the ItemPosition property to align the item.

// Scrolling with index
await MyGridView.SmoothScrollIntoViewWithIndexAsync(index: int, itemPlacement: ItemPlacement, disableAnimation: bool, scrollIfVisible: bool, additionalHorizontalOffset: int, additionalVerticalOffset: int);

// Scrolling with item
await MyGridView.SmoothScrollIntoViewWithItemAsync(item: object, itemPlacement: ItemPlacement, disableAnimation: bool, scrollIfVisible: bool, additionalHorizontalOffset: int, additionalVerticalOffset: int);

We can use this extension to make the selected item always centered:

<Page x:Class="ExtensionsExperiment.Samples.ListViewExtensions.SmoothScrollIntoViewSample"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      mc:Ignorable="d">

    <ListView ItemsSource="{x:Bind Items, Mode=OneWay}"
              ScrollViewer.HorizontalScrollBarVisibility="Visible"
              ScrollViewer.HorizontalScrollMode="Enabled"
              SelectionChanged="ListView_SelectionChanged">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
    </ListView>
</Page>
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using CommunityToolkit.WinUI;

#if WINAPPSDK
using ListView = Microsoft.UI.Xaml.Controls.ListView;
#else
using ListView = Windows.UI.Xaml.Controls.ListView;
#endif

namespace ExtensionsExperiment.Samples.ListViewExtensions;

[ToolkitSample(id: nameof(SmoothScrollIntoViewSample), "SmoothScrollIntoView Extension", description: "A sample for showing how to use the SmoothScrollIntoViewWithIndexAsync API.")]
public sealed partial class SmoothScrollIntoViewSample : Page
{
    public ObservableCollection<string> Items { get; set; } = new();

    public SmoothScrollIntoViewSample()
    {
        Items = GetOddEvenSource(201);

        this.InitializeComponent();
    }

    private async void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (sender is ListView listView)
        {
            await listView.SmoothScrollIntoViewWithIndexAsync(listView.SelectedIndex, ScrollItemPlacement.Center, false, true);
        }
    }

    private ObservableCollection<string> GetOddEvenSource(int count)
    {
        ObservableCollection<string> oddEvenSource = new();

        for (int number = 0; number < count; number++)
        {
            var item = (number % 2) == 0 ? $"{number} - Even" : $"{number} - Odd";
            oddEvenSource.Add(item);
        }

        return oddEvenSource;
    }
}