WPF ListBox ItemContainerStyle 设置BackGround 和 BorderBrush 无效

今天更改ListBox,用到ItemContainerStyle设置样式,设置Style.Triggers时,BackGround和BorderBrush均无效,其他效果正常。

翻看WPF编程宝典,发现代码没问题,下载源码之后,发现效果一样不行。在群里求助之后,得到解决。win8问题,编程宝典的作者用的是win7,xp也正常,唯独win8没有效果。

原问题链接:http://stackoverflow.com/questions/491293/why-cant-i-set-the-background-color-of-a-selected-listboxitem-in-wpf/807575#807575

按照链接中的方法,修改ListBox模板即可。

主要添加一个style重写ListBoxItem模板,在代码中加入你要修改的样式即可。

    <Style TargetType="{x:Type ListBoxItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <Border x:Name="Bd" SnapsToDevicePixels="true" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}">
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" x:Name="contentPresenter"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="#D4E9FE"/>
                        </Trigger>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="Background" Value="#1D82DA"/>
                        </Trigger>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsSelected" Value="true"/>
                                <Condition Property="Selector.IsSelectionActive" Value="false"/>
                            </MultiTrigger.Conditions>
                            <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
                        </MultiTrigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
模板代码

 

posted @ 2013-11-17 00:25  xiaocong_soft  阅读(2672)  评论(1编辑  收藏  举报