wpfxamldatatemplatestaticresource

Set an image as a Button's content in style


I have a WPF button defined like this:

<Button Style="{StaticResource RevertButtonStyle}" />

Here is how the style looks:

<Style x:Key="RevertButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Height" Value="25" />
    <Setter Property="Width" Value="20" />
    <Setter Property="Margin" Value="3,0,0,0" />
</Style>

How do I change the style to specify the Content to use an image called "revert.png"?

Thanks.


Solution

  • You can't use set the Content property to an instance of the Image control, as then the Image could be used by more than one Button. This would result in a "visual is already the child of another visual" exception.

    Instead, you can use a DataTemplate like so:

    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <Image Source="revert.png" />
            </DataTemplate>
        </Setter.Value>
    </Setter>
    

    Obviously you may need to adjust the image's source URI.