WPF changes the visual state of the data table when selected in the list

If I have a WPF ListBox that has a base ItemTemplate that contains a user control, how can I tell the user control in the DataTemplate to change its visual state when it is selected in the ListBox

Thanks so much for any help you can give.

+4
source share
1 answer

You can create a ListBoxItem style to run in the IsSelected property. Here is an example:

and then you use it like this:

 <ListBox ItemContainerStyle="{StaticResource yourListBoxItemStyle}"> 

or directly in the ListBox :

 <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> ... </Style> </ListBox.ItemContainerStyle> 

Edit:

Here is a complete example with an ItemTemplate and ItemContainerStyle that places a translucent layer on top of a selected item.

 <Grid> <Grid.Resources> <x:Array Type="sys:String" x:Key="sampleData"> <sys:String>Red</sys:String> <sys:String>Green</sys:String> <sys:String>Blue</sys:String> </x:Array> <DataTemplate x:Key="listBoxItem"> <Rectangle Fill="{Binding}" Width="100" Height="100"/> </DataTemplate> <Style TargetType="ListBoxItem" x:Key="listBoxItemStyle"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <Grid> <ContentPresenter /> <Rectangle x:Name="Rectangle" Fill="Black" Opacity="0"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="true"> <Setter TargetName="Rectangle" Property="Opacity" Value="0.5"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </Grid.Resources> <ListBox ItemsSource="{StaticResource sampleData}" ItemTemplate="{StaticResource listBoxItem}" ItemContainerStyle="{StaticResource listBoxItemStyle}" /> </Grid> 

Edit

After the comment, here is the version using the "unified" template:

 <Style TargetType="ListBoxItem" x:Key="listBoxItemStyle"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <Grid> <Rectangle Name="Rectangle" Fill="{Binding}" Width="100" Height="100" Opacity="1"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="true"> <Setter TargetName="Rectangle" Property="Opacity" Value="0.5"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> 
+7
source

Source: https://habr.com/ru/post/1334620/


All Articles