2015-10-14 117 views
1

我有一个ListBoxItemsSource只是一个字符串列表。我有一个改变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; 
    } 
} 

这里是我的MyStyleBlueMyStyleBlack

<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应该将样式更改为MyStyleBlueMyStyleBlue应该改变前景为蓝色(但它不)。我究竟做错了什么?

我看到this question这说StyleSelector s将不会工作,如果ItemContainerStyle设置。但那么我怎么用StyleSelectorItemContainerStyle设置?有没有其他方法可以做我想做的事情?

回答

1

当您使用ItemStyleSelector时,项目样式将从该样式选择器返回,因此同时设置ItemContainerStyle不起作用。

但是,这并不重要,因为从MyStyleSelector返回的样式已基于MyStyleBase。根本不需要将ItemContainerStyle设置为MyStyleBase

+0

谢谢,所以我删除了'Listbox'的样式中'ItemContainerStyle'的setter,并将contentPresenter更改为''并将' Foreground' setters到'

相关问题