我有一个带有DataTemplate的ListBox。我正在尝试将列表框中所选项目的文本/前景颜色更改为白色。我已经认真尝试过30种在Google上找到的不同方法。我就是无法正常工作。如何更改前景色?
另外,我想指出的是,我不想依赖使用SystemColors的方法,因为我读到它在.net 4.5中不起作用,所以当我们将应用程序移至4.5有一天。这是我的列表框xaml:
<ListBox Grid.Row="1" x:Name="Alerts" ItemsSource="{Binding Alerts}" HorizontalContentAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled" AlternationCount="2">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal">
<Label Content="{Binding Type}" HorizontalAlignment="Left" Padding="1,1,1,0" />
<Label Content=" - " Padding="1,1,1,0"></Label>
<Label Content="{Binding Date}" HorizontalAlignment="Left" Padding="1,1,1,0" />
</StackPanel>
<Label Grid.Row="1" Content="{Binding Message}" HorizontalAlignment="Left" Margin="0" Padding="1,0,1,1" />
</Grid>
<Button Grid.Column="1"
CommandParameter="{Binding .}"
Command="{Binding Path=DataContext.Commands.RemoveAlertCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"
Content="X" HorizontalAlignment="Right" Width="Auto" Height="Auto" Foreground="#FFD40000" FontWeight="Bold" VerticalAlignment="Center" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="LightGray"></Setter>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="Ivory"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
最佳答案
那这个呢:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
在使用TextBlocks的DataTemplate中,
Foreground
属性将被简单地继承:<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
在带有标签控件的DataTemplate中,
Foreground
值继承不起作用(请参见here原因)。但您可能总是像这样绑定到ListBoxItem的Foreground属性:<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding}"
Foreground="{Binding Foreground,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=ListBoxItem}}"/>
</DataTemplate>
</ListBox.ItemTemplate>
或者,您可以简单地用TextBlocks替换Labels。
关于c# - 如何在列表框中更改所选项目的“文本”前景色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14803225/