Home > Software design >  Set a path stroke color for a disabled button
Set a path stroke color for a disabled button

Time:01-25

I'd like to add a button to my application that contains a simple vector shape as content. That shape draws an arrow. When the button is enabled, the arrow shall be black. When the button is disabled, the arrow shall be grey. Can WPF do this, and how?

This is my failed attempt:

<Button
    Name="BackButton"
    Width="21" Height="21"
    Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
    Click="BackButton_Click"
    IsEnabled="False">
    <Path
        x:Name="path"
        Data="M6,1 L2,5 L6,9 M2,5 L11,5"
        Stroke="Black" StrokeThickness="1.5">
    </Path>
    <Button.Triggers>
        <Trigger Property="Button.IsEnabled" Value="False">
            <Setter TargetName="path" Property="Stroke" Value="Gray" />
        </Trigger>
    </Button.Triggers>
</Button>

The compiler points to the TargetName attribute and says it doesn't know that name. Apparently it wasn't able to look it up a few lines further up. There's also an error for the Property attribute.

The button has a click event handler and should be managed through code-behind. Maybe I'll change that to a command and control it from the view model, not sure yet what the requirements are. But the button can be disabled either way, and that must be visible.

The target framework is .NET 4.8.

CodePudding user response:

TargetName is meant to specify an element in a ControlTemplate. Move the Trigger to the Triggers collection of a ControlTemplate or a Style.

Or use a DataTrigger in a Path Style and make sure not to set the Stroke directly on the Path.

<Path Data="M6,1 L2,5 L6,9 M2,5 L11,5" StrokeThickness="1.5">
    <Path.Style>
        <Style TargetType="Path">
            <Setter Property="Stroke" Value="Black"/>
            <Style.Triggers>
                <DataTrigger
                    Binding="{Binding IsEnabled,
                              RelativeSource={RelativeSource AncestorType=Button}}"
                    Value="False">
                    <Setter Property="Stroke" Value="Gray" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Path.Style>
</Path>
  • Related