开发者

Foreground of Button not changing in property trigger

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜