How to invoke OnSelectionChanged on Selector and apply Style with Trigger

Emon Haque 3,176 Reputation points
2020-12-01T10:58:09.367+00:00

Here's the Custom Control, CustomSelector:

public class CustomSelector : Selector
{
    static CustomSelector() { DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomSelector), new FrameworkPropertyMetadata(typeof(CustomSelector))); }
    protected override void OnSelectionChanged(SelectionChangedEventArgs e) { Debug.WriteLine("OnSelectionChanged"); }
}

and in Themes\Generic.xaml I've these for CustomSelector:

<Style TargetType="{x:Type local:CustomSelector}">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel/>
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:CustomSelector}">
                <ScrollViewer>
                    <ItemsPresenter/>
                </ScrollViewer>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <Border x:Name="border" Padding="2 0 2 0">
                    <TextBlock Text="{Binding}"/>
                </Border>
                <DataTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter TargetName="border" Property="Border.Background" Value="SkyBlue"/>
                        <Setter TargetName="border" Property="Border.BorderBrush" Value="Red"/>
                        <Setter TargetName="border" Property="Border.BorderThickness" Value="1"/>
                    </Trigger>
                    <Trigger Property="Selector.IsSelected" Value="True">
                        <Setter TargetName="border" Property="Border.Background" Value="LightGray"/>
                        <Setter TargetName="border" Property="Border.BorderBrush" Value="Red"/>
                        <Setter TargetName="border" Property="Border.BorderThickness" Value="1"/>
                    </Trigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

When I hover over items IsMouseOver styles get applied on items BUT when I left click on an Item it neither applies the style in Selector.IsSelected nor invokes the protected override void OnSelectionChanged function.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,710 questions
{count} votes