Jibran Khan
Jibran Khan

Reputation: 3256

SurfaceListBoxItem Trigger IsSelected

Good day!

I have SurfaceListBox and its Item template designed using XAML. I have added a trigger of IsSelected = true which works fine however I want to deselect it in case the same item is selected again. I am able to do it if another item is selected but not able to deselect the same item.

<ControlTemplate.Triggers>
    <Trigger Property="IsSelected" Value="True">
        <Setter TargetName="SelectTxt" Property="Visibility" Value="Collapsed" />
        <Setter TargetName="DeselectTxt" Property="Visibility" Value="Visible" />
        <Setter TargetName="SelectionBorder" Property="Background" Value="#3ab175" />
        <Setter TargetName="CheckMark" Property="Visibility" Value="Visible" />
        <Setter TargetName="CheckBorder" Property="BorderBrush" Value="White" />
    </Trigger>
</ControlTemplate.Triggers>

I want to revert all the setter properties on deselection.

Upvotes: 0

Views: 94

Answers (1)

dhilmathy
dhilmathy

Reputation: 2868

You can add a CheckBox to your ItemTemplate to achieve Selection & DeSelection. In this, CheckBox's Checked property is binded to IsSelected of your ListViewItem. So, your existing Triggers would work as it is.

<ListView.ItemTemplate>
    <DataTemplate>
        <CheckBox Content="{Binding}" 
                  Width="{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}}"
                  IsChecked="{Binding IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}}"/>
    </DataTemplate>
</ListView.ItemTemplate>

If you do not want to see the CheckBox, you can use ToggleButton to get the same functionality. Like,

<ListView.ItemTemplate>
    <DataTemplate>
        <ToggleButton Content="{Binding}" 
                      Width="{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}}"
                      IsChecked="{Binding IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}}">
            <ToggleButton.Template>
                <ControlTemplate TargetType="ToggleButton">
                    <Border BorderThickness="0">
                        <ContentPresenter/>
                    </Border>
                </ControlTemplate>
            </ToggleButton.Template>
        </ToggleButton>
    </DataTemplate>
</ListView.ItemTemplate>

Note: Use appropriate property name for the CheckBox & ToggleButton content binding.

Upvotes: 1

Related Questions