Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataTrigger Works for Image but not for Path

The following dims the image when I disable the button and show clearly when enabled:

<Style TargetType="{x:Type Image}">
    <Style.Triggers>
      <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type UIElement}, AncestorLevel=1}, Path=IsEnabled}" Value="False">
      <Setter Property="Opacity" Value="0.25"></Setter>
    </DataTrigger>
    </Style.Triggers>
</Style>
...
<Button Name="btnPageFirst" IsEnabled="False">
    <Image Source="..\Resources\imgMoveFirst.png" />
</Button>

I want to do a similar effect but with Path. I want to gray the image. But it does not gray and there is no error.

<Style TargetType="{x:Type Path}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type UIElement}, AncestorLevel=1}, Path=IsEnabled}" Value="False">
            <Setter Property="Fill" Value="Gray"></Setter>
        </DataTrigger>
    </Style.Triggers>
</Style>
...
<Button Name="btnPageFirst" IsEnabled="False">
    <Path Data="F1M820.557,535.025L838.189,535.024 817.857,555.36 857.82,555.36 857.82,568.301 817.998,568.301 838.226,588.531 820.557,588.499 793.82,561.765 820.557,535.025z" Stretch="Uniform" Fill="DodgerBlue" Width="16" Height="16" Margin="0,0,0,0" />
</Button>

like image 798
Bydia Avatar asked Feb 21 '23 13:02

Bydia


1 Answers

There is a precedence order which is used to calculate the values of the dependency properties during runtime.

The oversimplified precedence list:

  1. Local value (what you set on the control)
  2. Triggers
  3. Style setters

Your problem is that you set Fill="DodgerBlue" on your path and because it has higher precedence then the Trigger that is way you don't see the fill change. Also that is why it works for your Image because there you don't set the Opacity directly.

To make it work:

  1. Remove the Fill="DodgerBlue" from your path
  2. Set it in your style:

    <Style TargetType="{x:Type Path}">
        <Style.Setters>
            <Setter Property="Fill" Value="DodgerBlue"/>
        </Style.Setters>
        <Style.Triggers>
           <!-- ... -->
        </Style.Triggers>
    </Style>
    

As a side note: if you always "inside" in a button you can rewrite the RelativeSource to:

RelativeSource={RelativeSource AncestorType={x:Type Button}}
like image 89
nemesv Avatar answered Mar 04 '23 13:03

nemesv