在ListBoxItem的Style中无法设置Foreground解决思路

在ListBoxItem的Style中无法设置Foreground
本帖最后由 bonat 于 2014-08-03 18:53:32 编辑
写了一个ListBoxItem的Style,其中有个触发器,满足条件设置字体颜色为Red,但是就是没效果,请大家帮忙。代码如下:
<Style TargetType="ListBoxItem">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <StackPanel>
                            <Label Content="{Binding Id}" Foreground="Blue" />
                        </StackPanel>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>
                        <Condition Binding="{Binding Path=Id}" Value="1" />
                    </MultiDataTrigger.Conditions>
                    <MultiDataTrigger.Setters>
                        <Setter Property="Foreground" Value="Red" />
                    </MultiDataTrigger.Setters>
                </MultiDataTrigger>
            </Style.Triggers>
        </Style>

红色的代码没效果,什么原因呢?
------解决方案--------------------
错误原因是Trigger改动的是ListBoxItem的颜色,而不是Label的颜色(那个<Label Content="{Binding Id}" Foreground="Blue" />)。

两种改法,
一、Label的颜色绑定到ListBoxItem的颜色上,改变ListBoxItem的颜色就会改变Label的颜色。
<Label Content="{Binding Id}" Foreground="{Binding Foreground,RelativeSource={RelativeSource AncestorType=ListBoxItem}}" />

二、采用DataTemplate.Triggers(代码比较少和清晰):

<Style TargetType="ListBoxItem">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <StackPanel>
                    <Label Name="itemLable" Content="{Binding Id}" Foreground="Black" />
                </StackPanel>
                <DataTemplate.Triggers>
                    <DataTrigger Binding="{Binding Id}" Value="1">
                        <Setter Property="Foreground" Value="Red" TargetName="itemLable"/>
                    </DataTrigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>