我有一个ListBox
其ItemsSource
只是一个字符串列表。我有一个改变ListBoxItem
的模板的样式。
这就是:使用StyleSelector和ItemContainerStyle
<Style x:Key="MyStyleBase" TargetType="{x:Type ListBoxItem}" >
<Setter Property="Margin" Value="2" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<StackPanel x:Name="stackPanel">
<CheckBox Focusable="False"
IsChecked="{Binding Path=IsSelected, Mode=TwoWay,
RelativeSource={RelativeSource TemplatedParent} }">
<ContentPresenter/>
</CheckBox>
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter TargetName="stackPanel" Property="Background" Value="LightBlue" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="stackPanel" Property="Background" Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我用另一种样式应用这种风格到ListBox
:
<Style x:Key="Style" TargetType="ListBox">
<Setter Property="AlternationCount" Value="2"/>
<Setter Property="ItemContainerStyle" Value="{StaticResource MyStyleBase}"/>
</Style>
现在这个伟大的工程,直到我希望每个ListBoxItem
文本的前景被改变基于它的字符串值。 我使用的是StyleSelector
此:
class MyStyleSelector : StyleSelector
{
public override Style SelectStyle(object item, DependencyObject container)
{
if((string)item == "Avatar")
return Application.Current.MainWindow.FindResource("MyStyleBlue") as Style;
return Application.Current.MainWindow.FindResource("MyStyleBlack") as Style;
}
}
这里是我的MyStyleBlue
和MyStyleBlack
:
<Style x:Key="MyStyleBlack" BasedOn="{StaticResource MyStyleBase}" TargetType="{x:Type ListBoxItem}">
<Setter Property="Foreground" Value="Black"></Setter>
</Style>
<Style x:Key="MyStyleBlue" BasedOn="{StaticResource MyStyleBase}" TargetType="{x:Type ListBoxItem}">
<Setter Property="Foreground" Value="Blue"></Setter>
</Style>
当我在ListBoxItem
字符串“阿凡达”这是行不通的。它只显示通常的MyStyleBase
(前景不变)。但如果ListBoxItem
是“头像”,StyleSelector
应该将样式更改为MyStyleBlue
。 MyStyleBlue
应该改变前景为蓝色(但它不)。我究竟做错了什么?
我看到this question这说StyleSelector
s将不会工作,如果ItemContainerStyle
设置。但那么我怎么用StyleSelector
与ItemContainerStyle
设置?有没有其他方法可以做我想做的事情?
谢谢,所以我删除了'Listbox'的样式中'ItemContainerStyle'的setter,并将contentPresenter更改为' '并将' Foreground' setters到'