【问题标题】:Setter precedence overriding in WPF?WPF中的设置器优先级覆盖?
【发布时间】:2010-12-07 19:48:45
【问题描述】:

查看以下示例中的“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>

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

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

【问题讨论】:

    标签: .net wpf .net-3.5 datatrigger


    【解决方案1】:

    您应该能够使用两个数据触发器来执行此操作,一个为真,一个为假。

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

    【讨论】:

    • 哦,当然,很好的解决方法...想知道是否需要压倒一切的优先级? (在这种情况下没有,但在其他一些极端情况下......)
    • 我不确定是否有一种方法可以轻松绑定它并覆盖它,而无需执行类似我的解决方案的操作...我认为您可以绑定它并更改绑定属性,或者使用更改数据触发器如上...
    • AFAIK 来自第二个DataTriggerSetter 可以直接在Style 中指定。它将作为默认值,触发器将覆盖它。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 2018-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多