我有一个ListBox,它的ItemsSource只是一个字符串列表。我有一个样式,可以改变ListBoxItem的模板。
这就是它:
<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(前景不变)。但是如果StyleSelector是“阿凡达”,ListBoxItem应该会把样式改成MyStyleBlue。MyStyleBlue应该将前景更改为蓝色(但它没有)。我做错了什么?
我看到了this question,上面写着如果设置了ItemContainerStyle,StyleSelectors将不起作用。但是,如何通过ItemContainerStyle集使用StyleSelector呢?有没有其他方法可以做我想做的事?
发布于 2015-10-15 01:07:37
使用ItemStyleSelector时,项目样式是从该StyleSelector返回的,因此同时设置ItemContainerStyle没有任何效果。
但是,这并不重要,因为从MyStyleSelector返回的样式已经基于MyStyleBase。根本不需要将ItemContainerStyle也设置为MyStyleBase。
https://stackoverflow.com/questions/33130948
复制相似问题