0

I have a collection of view model objects bound to a ListView. I want to add a selection indicator for the selected ListViewItem, like in the dark blue rectangle below:

ListViewItem selection indicator image

What is the right way to implement this?

What I plan to do: Add an IsSelected field to my view model, set it to true when item is selected and false otherwise, then bind it to visibility of the NotificationSelectedIndicator rectangle.

Please take a look at code below for reference:

<DataTemplate x:Key="NotificationListViewItemTemplate" x:Name="NotificationsListViewDataTemplate" x:DataType="local:NotificationViewModel">
    <StackPanel Orientation="Horizontal">
        <Rectangle Name="NotificationSelectedIndicator" Fill="{ThemeResource SystemAccentColor}" HorizontalAlignment="Left" Width="5" Height="Auto" Margin="-11, 0, 0, 0" Visibility="{x:Bind Converter={StaticResource BoolToVisConverter}, Path=IsSelected}"/>

        <Grid Height="Auto" Width="Auto" Padding="0, 10, 0, 10">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>

            ...
        </Grid>
    </StackPanel>
</DataTemplate>

Is there a simpler way to add the indicator?

In the documentation page for ListViewItem, there's a resource called ListViewItemSelectionIndicatorVisualEnabled, but these are only supported for WinUI.

Thank you for any help in advance!

1 Answers1

1

Instead of bringing extra fields into the model, you can try to wire-up on appropriate properties of ListViewItem itself and use style triggers to show/hide something:

<Style x:Key="MyStyle" TargetType="{x:Type ListViewItem}">
  <Style.Triggers>
    <Trigger Property="IsMouseOver" Value="true">...</Trigger>
    <Trigger Property="IsSelected" Value="true">...</Trigger>
    ...

https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.listviewitem?view=winrt-22000#properties

Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42