ItemContainerStyle阻止ItemContainerStyleSelector

时间:2011-12-15 15:06:45

标签: wpf listboxitem itemcontainerstyle

我有代码:

<ListBox Style="{StaticResource DeviceListBox}"
                 ItemsSource="{Binding MeterList, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"
                 SelectedItem="{Binding CurrentMeter, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"
                 ItemContainerStyleSelector="{StaticResource DeviceListItemStyleSelector}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Style="{StaticResource DeviceListText}" Text="{Binding Name}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>

我使用ItemContainerStyleSelector="{StaticResource DeviceListItemStyleSelector}"更改每个列表框项目中的背景颜色(例如黑色或银色,请参阅 - http://msdn.microsoft.com/en-us/library/system.windows.controls.styleselector.aspx)。它有效。但是,如果我在ItemContainerStyle="{StaticResource DeviceListItemStyle}"中添加DeviceListItemStyle来创建一些触发器等,则DeviceListItemStyleSelector不起作用。请帮帮我!)

1 个答案:

答案 0 :(得分:6)

ItemContainerStyleSelector根据某些逻辑选择样式,因此显然手动设置样式将覆盖您的选择器应用的样式。

为什么不在ItemContainerStyle设置背景颜色?

<Style x:Key="DeviceListItemStyle" TargetType="{x:Type ListBoxItem}">
    <Setter Property="Background" Value="Black" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsSilver}" Value="True">
            <Setter Property="Background" Value="Silver" />
        </DataTrigger>
    </Style.Triggers>
</Style>