Mik*_*aas 1 c# wpf xaml wpf-controls
我有一个带有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>
Run Code Online (Sandbox Code Playgroud)
那这个呢:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
Run Code Online (Sandbox Code Playgroud)
在使用TextBlocks的DataTemplate中,该Foreground属性将被简单地继承:
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)
在带有Label控件的DataTemplate中,Foreground值继承不起作用(请参阅此处原因).但是你可能总是绑定到ListBoxItem的Foreground属性,如下所示:
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding}"
Foreground="{Binding Foreground,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=ListBoxItem}}"/>
</DataTemplate>
</ListBox.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)
或者您可以简单地用TextBlocks替换标签.
| 归档时间: |
|
| 查看次数: |
3334 次 |
| 最近记录: |