How can I change the Foreground color of a TextBlock with a Trigger?

user1910001 picture user1910001 · Dec 17, 2012 · Viewed 14.2k times · Source

I want to change foreground color of a TextBlock from dependencyproperty.
But I don't change textblock color.
I don't know this problem in my code.
How can I change the foreground color of a TextBlock with a Trigger?

XAML:

<TextBlock Name="TestBlock" Text="Test color" >
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Style.Triggers>
                <Trigger Property ="IsMouseOver" Value="True">
                    <Setter Property= "Foreground" Value="Gray"/>
                </Trigger>
                <DataTrigger Binding="{Binding Path=TestColorMode2, RelativeSource={RelativeSource AncestorType={x:Type local:Window1}}}" Value="0">
                    <Setter Property="Foreground" Value="Red" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=TestColorMode2, RelativeSource={RelativeSource AncestorType={x:Type local:Window1}}}" Value="1">
                    <Setter Property="Foreground" Value="Blue" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=TestColorMode2, RelativeSource={RelativeSource AncestorType={x:Type local:Window1}}}" Value="2">
                    <Setter Property="Foreground" Value="Green" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=TestColorMode2, RelativeSource={RelativeSource AncestorType={x:Type local:Window1}}}" Value="3">
                    <Setter Property="Foreground" Value="Black" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

CODE:

public static DependencyProperty TestColorModeProperty = DependencyProperty.Register("TestColorMode", typeof(int), typeof(UpdateProgressItem));

public int TestColorMode
{
    get { return (int)GetValue(TestColorModeProperty); }
    set { SetValue(TestColorModeProperty, value); }
}

            ....

private void button1_Click(object sender, RoutedEventArgs e)
{
    TestColorMode++;
}

Answer

Ramin picture Ramin · Dec 17, 2012

Specify the type too:

<Trigger Property="TextBlock.IsMouseOver" Value="true">
     <Setter Property="TextBlock.Foreground" Value="Gray" />
</Trigger>