2

I have a style

<Style x:Key="HomeButtonStyle" TargetType="Button">
    <Setter Property="Height" Value="32"/>
    <Setter Property="Width" Value="32"></Setter>
    <Setter Property="Content">
        <Setter.Value>
            <Image Source="/Images/HOME.png"></Image>
        </Setter.Value>
    </Setter>
</Style>

and I have some xaml in a control

    <StackPanel Grid.Row="0" Orientation="Horizontal">
        <Button Style="{DynamicResource HomeButtonStyle}" />
        <Button Style="{DynamicResource HomeButtonStyle}" />
        <Button Style="{DynamicResource HomeButtonStyle}" />
        <Button Style="{DynamicResource HomeButtonStyle}" />
    </StackPanel>

However the image is only shown in the last button.

My questions are why? and how to make the image show in all the buttons?

4

2 回答 2

7

In your style you should set ContentTemplate instead of Content directly.

<Setter Property="ContentTemplate">
  <Setter.Value>
     <DataTemplate>
       <Image Source="/Images/HOME.png"></Image>
     </DataTemplate>
    </Setter.Value>
</Setter>
于 2013-02-07T13:56:26.353 回答
4
<Image x:Key="HomeImage" x:Shared="false" Source="/Images/Home.jpg" />
<Style x:Key="HomeButtonStyle" TargetType="Button">
    <Setter Property="Height" Value="32"/>
    <Setter Property="Width" Value="32"></Setter>
    <Setter Property="Content" Value="{StaticResource HomeImage}" />
</Style>

Your code is reusing Image control which was already added to another visual tree. Use x:shared to create a new instance of Image control each time and all will be fine. More info here.

于 2013-02-07T13:58:17.903 回答