Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a trigger to set a textblock foreground on mouseover

Tags:

wpf

xaml

I am trying to set block so its foreground color will change every time the mouse cursor goes over it, and this is my code:

<TextBlock Foreground="blue" Margin="18,234,5,-2" Grid.RowSpan="3">
    <Underline>Remove Message</Underline>
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Style.Triggers>
                <Trigger Property ="IsMouseOver" Value="True">
                    <Setter Property= "Foreground" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

When I try to change the setter property to any other, for example FontSize="30", the event does occur.

like image 377
Nadav Avatar asked Dec 17 '10 15:12

Nadav


People also ask

How do I override the foreground property of a textblock?

If that style is applied to a TextBlock the property Foreground will be set to ‘Blue’. You can override the Foreground Property when you declare a value for Foreground locally at the place where you declare the TextBlock element. See my Dependency Property article for more information about the value evaluation order.

What is the default color of a textblock's foreground?

The default is Black. The following example shows how to set the Foreground attribute of a TextBlock element.

How do I change the default text in a textblock?

You can change these defaults by changing the property values, or by applying a different style to specific TextBlock instances. You can change the foreground value for all default text by overriding the resource named DefaultTextForegroundThemeBrush in App.xaml.

What happens if I omit the targettype from a textblock?

If you omit the TargetType you always need to prefix the property name with the class type. It automatically applies your style to all TextBlock instances in the scope of the Style. Hint: Our Style is only in scope if it is contained in the Resource Dictionary of the XAML file.


1 Answers

That is because the properties set on a control override the one defined in the Style, so your Foreground="blue" will override whatever you set in the style. To fix this, you can move the Foreground="blue" in the style and remove it from the properties of the control.

<TextBlock Margin="18,234,5,-2" Grid.RowSpan="3">
      <Underline>Remove Message</Underline>
      <TextBlock.Style>
           <Style TargetType="TextBlock">
               <Setter Property= "Foreground" Value="Blue"/>
               <Style.Triggers>
                   <Trigger Property ="IsMouseOver" Value="True">
                        <Setter Property= "Foreground" Value="Red"/>
                   </Trigger>
               </Style.Triggers>
            </Style>
       </TextBlock.Style>
</TextBlock>
like image 142
Andrei Pana Avatar answered Sep 23 '22 19:09

Andrei Pana