UkoM
UkoM

Reputation: 305

Changing ellipse fill color inside a button

I want to change the ellipse fill color to green when the button is enabled.

   <Button x:Name="btn_Kaart2" Grid.Column="1" Grid.Row="2" IsEnabled="False">
        <Button.Template>
            <ControlTemplate>
                <Ellipse x:Name="ellipse_2" 
                         Height="35"
                         Stroke="Black"
                         Fill="Red"
                         Margin="-300,440,0,0"/>
            </ControlTemplate>
        </Button.Template>
    </Button>

Normally I would use ellipse_2.Fill = "Color" but that doesn't work, program can't find ellipse_2

Upvotes: 2

Views: 1749

Answers (1)

AntiHeadshot
AntiHeadshot

Reputation: 1130

You can use a databinding with RelativeSource to get this without any additional code

<Button x:Name="btn_Kaart2" Grid.Column="1" Grid.Row="2" IsEnabled="False">
    <Button.Template>
        <ControlTemplate>
            <Ellipse x:Name="ellipse_2" 
                Height="35"
                Margin="-300,440,0,0"
                Stroke="Black">
            <Ellipse.Style>
                <Style TargetType="Ellipse">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsEnabled, RelativeSource={RelativeSource AncestorType=Button}}" Value="false">
                            <Setter Property="Fill" Value="red"></Setter>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding IsEnabled, RelativeSource={RelativeSource AncestorType=Button}}" Value="true">
                            <Setter Property="Fill" Value="green"></Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Ellipse.Style>
            </Ellipse>
        </ControlTemplate>
    </Button.Template>
</Button>

It's important that the Ellipse itself has no Fill attribute.
You can try this by changing the IsEnabled value in the *.xaml and the color should change immediately in the designer.

Upvotes: 4

Related Questions