I want to apply a custom style to the selected item on a ListView in WinUI3.
My first thought was to look for a property on ListView to see if there was a style to be applied to the selected item, but no luck there. Next up was to use a DataTemplateSelector, for which I made the below block of code:
internal class ListViewSelectedItemSelector : DataTemplateSelector
{
public DataTemplate NormalTemplate { get; set; }
public DataTemplate SelectedTemplate { get; set; }
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
if (container is not ListViewBase listView)
{
throw new Exception($"{nameof(ListViewSelectedItemSelector)} can only be used on {nameof(ListViewBase)}");
}
return listView.SelectedItem == item ? SelectedTemplate : NormalTemplate;
}
}
But this proves impractical to work with since I need to declare 2 different data templates and maintain them together for just one tiny difference between them. This also becomes significantly more tedious when trying to change the selected item’s style while also using another DataTemplateSelector.
Is there a cleaner and more simple way to apply a style to only the selected item (or its container) in a ListView, ideally through XAML alone?