开发者

Foreground of Button not changing in property trigger

开发者 https://www.devze.com 2022-12-21 19:38 出处:网络
Why does this trigger work (Changing the foreground of the button to \"Red\" when the mouse is over) <Grid>

Why does this trigger work (Changing the foreground of the button to "Red" when the mouse is over)

<Grid>
 <Grid.Resources>
  <Style TargetType="{x:Type Button}">
   <Style.Triggers>
    <Trigger Property="IsMouseOver" Value="True">
     <Setter Property="Foreground" Value="Red"/>
    </Trigger>
   </Style.Triggers>
  </Styl开发者_运维技巧e>
 </Grid.Resources>
 <Button Content="Hello"/>
</Grid>

but not this trigger, when the foreground of the button is set to a color (in this case "Blue")?

<Grid>
 <Grid.Resources>
  <Style TargetType="{x:Type Button}">
   <Style.Triggers>
    <Trigger Property="IsMouseOver" Value="True">
     <Setter Property="Foreground" Value="Red"/>
    </Trigger>
   </Style.Triggers>
  </Style>
 </Grid.Resources>
 <Button Foreground="Blue" Content="Hello"/>
</Grid>


The local value of the button overrides the Style. Try:

<Grid>

    <Grid.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Foreground" Value="Blue"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Grid.Resources>

    <Button Content="Hello"/>

</Grid>


I know it's an old post, but this is the solution (in property trigger). Answer:

<Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="Blue"/>

The most logical way to do it:

<Setter Property="Foreground" Value="Blue"/>

But.. Don't work..


Just add a control template, then bind the ContentPresenter's TextElement.Foreground to {TemplateBinding Foreground} in your style:

<Grid>
    <Grid.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
                            <ContentPresenter TextElement.Foreground="{TemplateBinding Foreground}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Grid.Resources>
    <Button Content="Hello"/>
</Grid>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号