标签云

微信群

扫码加入我们

WeChat QR Code

I setting the selected item of a list box from the code behind as followsprivate void AvailableItem_Click(object sender, RoutedEventArgs e){object clicked = (e.OriginalSource as FrameworkElement).DataContext;var lbi = AvailableItem.ItemContainerGenerator.ContainerFromItem(clicked) as ListBoxItem;lbi.IsSelected = true;}I have added a trigger as follows to change the selected item background color<Style.Triggers><Trigger Property="IsSelected" Value="True"><Setter Property="Foreground" Value="White" /><Setter Property="Background" Value="Black"/></Trigger></Style.Triggers>The problem here is that the color does not change as expected. I tried adding trigger for IsSelected value to be false and it works, but IsSelected true is not triggered. I am confused as to why this happens.EDIT:Here is the complete binding code:<ListBoxHeight="600"Name="AvailableItem" Width="320" Grid.Column="1" ButtonBase.Click="AvailableItem_Click" Background="#00000000" BorderBrush="LightBlue" HorizontalContentAlignment="Stretch"><ListBox.ItemTemplate><DataTemplate><Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch"><Grid.ColumnDefinitions><ColumnDefinition Width="2*"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="*"/></Grid.RowDefinitions><TextBlock Text="{Binding Path = SomeText}" FontSize="14" Foreground="Black" Grid.Column="0" Grid.Row="0" VerticalAlignment="Center" Margin="0,0,0,0"/><Button Command="{Binding ElementName=root, Path=DataContext.SomeCommand}" Grid.Column="1" Grid.Row="0" HorizontalAlignment="Right" VerticalAlignment="Bottom" Background="#BF000000" BorderBrush="Transparent" Foreground="White" Content="..." Width="25" Height="25" Margin="5,0,5,0"></Button></Grid></DataTemplate></ListBox.ItemTemplate><ListBox.ItemContainerStyle><Style TargetType="{x:Type ListBoxItem}"><Style.Triggers><Trigger Property="IsSelected" Value="True"><Setter Property="Foreground" Value="Yellow" /><Setter Property="Background" Value="Red"/></Trigger><Trigger Property="IsSelected" Value="False"><Setter Property="Foreground" Value="Black" /><Setter Property="Background" Value="Transparent"/></Trigger></Style.Triggers></Style></ListBox.ItemContainerStyle>


How do you apply this style? Where do you set the TargetType of the style? How do you bind the ListBox style property to this style?

2019年04月22日22分05秒

DeanKuga Please see the edit.

2019年04月22日22分05秒

possible duplicate of Why can't I set the background color of a selected ListBoxItem in WPF?

2019年04月22日22分05秒