Search code examples
c#windowswin-universal-app

uwp win10 Listview SelectedItem Style


Is there a way to change the properties of a ListviewItem when this one is selected?

As an example, I want that a rectangle inside the ListviewItem to be Red when selected and Blue by default.

How to achieve this in an elegant manner?


Solution

  • You can set ListView.ItemContainerStyle to customize the style of ListViewItems used in the ListView.

    This page shows the default style: https://msdn.microsoft.com/en-us/library/windows/apps/mt299136.aspx

    In case of your example - you would change the Selected~Background properties in code similar to below:

    <ListView ...>
        <ListView.ItemContainerStyle>
            <Style
                TargetType="ListViewItem">
                <Setter Property="Template">
                    <Setter.Value>
        <ControlTemplate TargetType="ListViewItem">
          <ListViewItemPresenter
              ContentTransitions="{TemplateBinding ContentTransitions}"
              SelectionCheckMarkVisualEnabled="True"
              CheckBrush="{ThemeResource SystemControlForegroundBaseMediumHighBrush}"
              CheckBoxBrush="{ThemeResource SystemControlForegroundBaseMediumHighBrush}"
              DragBackground="{ThemeResource ListViewItemDragBackgroundThemeBrush}"
              DragForeground="{ThemeResource ListViewItemDragForegroundThemeBrush}"
              FocusBorderBrush="{ThemeResource SystemControlForegroundAltHighBrush}"
              FocusSecondaryBorderBrush="{ThemeResource SystemControlForegroundBaseHighBrush}"
              PlaceholderBackground="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}"
              PointerOverBackground="{ThemeResource SystemControlHighlightListLowBrush}"
              PointerOverForeground="{ThemeResource SystemControlHighlightAltBaseHighBrush}"
              SelectedBackground="{ThemeResource SystemControlHighlightListAccentLowBrush}"
              SelectedForeground="{ThemeResource SystemControlHighlightAltBaseHighBrush}"
              SelectedPointerOverBackground="{ThemeResource SystemControlHighlightListAccentMediumBrush}"
              PressedBackground="{ThemeResource SystemControlHighlightListMediumBrush}"
              SelectedPressedBackground="{ThemeResource SystemControlHighlightListAccentHighBrush}"
              DisabledOpacity="{ThemeResource ListViewItemDisabledThemeOpacity}"
              DragOpacity="{ThemeResource ListViewItemDragThemeOpacity}"
              ReorderHintOffset="{ThemeResource ListViewItemReorderHintThemeOffset}"
              HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
              VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
              ContentMargin="{TemplateBinding Padding}"
              CheckMode="Inline"/>
        </ControlTemplate>