Search code examples
c#wpfwindows-phone-8

Change circle button background image on click in WPF


I have a circle button below

<Button  x:Name="btnLight" Width="72" Height="72" Content="" Margin="180,0,372,94" VerticalAlignment="Bottom" d:LayoutOverrides="VerticalAlignment">
            <Button.Template>
                <ControlTemplate>
                    <Grid>
                        <Ellipse>
                            <Ellipse.Fill>
                                <ImageBrush ImageSource="Images/light-off.jpg"/>
                            </Ellipse.Fill>
                        </Ellipse>
                    </Grid>
                </ControlTemplate>
            </Button.Template>
    </Button>

How do I change the background image (Images/light-on.jpg) when I click it? Thank you!


Solution

  • Wow! You have been given some complicated answers here... you're all doing too much work!!! This question has a really simple solution. First, let's sort out this ControlTemplate the way it should be:

    <Button x:Name="btnLight" Width="72" Height="72" Content="" Margin="180,0,372,94" 
        VerticalAlignment="Bottom">
        <Button.Template>
            <ControlTemplate>
                <Ellipse Name="Ellipse" Fill="{TemplateBinding Background}" />
            </ControlTemplate>
        </Button.Template>
    </Button>
    

    Now, you can add a really simple Style to perform your image change:

    <Style TargetType="{x:Type Button}">
        <Setter Property="Button.Background">
            <Setter.Value>
                <ImageBrush ImageSource="Images/Add_16.png" />
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="Button.IsPressed" Value="True">
                <Setter Property="Button.Background">
                    <Setter.Value>
                        <ImageBrush ImageSource="Images/Copy_16.png" />
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>