Setter优先级覆盖WPF?

时间:2009-10-18 18:33:09

标签: .net wpf .net-3.5 datatrigger

在下面的例子中查看“THIS LINE ####”这一行。

<ListBox Grid.Row="0" x:Name="listBoxServers">
<ListBoxItem HorizontalContentAlignment="Stretch">
    <StackPanel>
        <TextBlock><Run Text="My computer"/></TextBlock>
        <TextBlock Foreground="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}">
            <TextBlock.Style>
                <Style>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}" Value="True">
                            <Setter Property="TextBlock.Foreground" Value="White" /> <!-- THIS LINE #### How can I get this work? -->
                            <Setter Property="TextBlock.Background" Value="Blue" /> <!-- This line here for debugging purposes (to show that these really are called) -->
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
            <Run Text="localhost"/>
        </TextBlock>
    </StackPanel>
</ListBoxItem>
</ListBox>

如何获取以下触发器来覆盖值?

(顺便说一句,上面的例子只是压缩的。(在实际应用中,Style就在它自己的资源中。)

2 个答案:

答案 0 :(得分:4)

This post可能会解释为什么在为属性分配了本地值时触发器不会触发。

答案 1 :(得分:2)

您应该可以使用两个数据触发器执行此操作,一个用于true,一个用于false。

    <TextBlock>
        <TextBlock.Style>
            <Style>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}" Value="True">
                        <Setter Property="TextBlock.Foreground" Value="White" />
                        <Setter Property="TextBlock.Background" Value="Blue" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}" Value="False">
                        <Setter Property="TextBlock.Foreground" Value="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBlock.Style>
        <Run Text="localhost"/>
    </TextBlock>