ItemContainerStyle blocks ItemContainerStyleSelector

老子叫甜甜 提交于 2019-12-23 05:59:31

问题


I have the code:

<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>

I use ItemContainerStyleSelector="{StaticResource DeviceListItemStyleSelector}" to change background color in each listbox items (e.g. black or silver, see - http://msdn.microsoft.com/en-us/library/system.windows.controls.styleselector.aspx). And it works. But if I add ItemContainerStyle="{StaticResource DeviceListItemStyle}" to create some triggers etc in DeviceListItemStyle then DeviceListItemStyleSelector doesn't work. Help me, please!)


回答1:


The ItemContainerStyleSelector selects a Style based on some logic, so obviously setting the Style manually will overwrite whatever Style your Selector applied.

Why don't you just set the background color in your 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>


来源:https://stackoverflow.com/questions/8522156/itemcontainerstyle-blocks-itemcontainerstyleselector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!