Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Button's Content to <Image> via Styles

Can't get this to work:

<UserControl>
    <UserControl.Resources>
        <ResourceDictionary>
            <Style x:Key="TestStyle" TargetType="{x:Type Button}">
                <Setter Property="Button.Content">
                    <Setter.Value>
                        <Image Source="D:\Temp\dictionary16.png"/>
                    </Setter.Value>
                </Setter>
            </Style>
        </ResourceDictionary>
    </UserControl.Resources>
    <StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
        <Button Style="{StaticResource TestStyle}"/>
        <Button Style="{StaticResource TestStyle}"/>
    </StackPanel>
</UserControl>

This code throws the following exception (pointing to the second button):

Specified element is already the logical child of another element. Disconnect it first.

like image 841
Reini Avatar asked Jun 15 '11 11:06

Reini


Video Answer


2 Answers

The style creates one instance of the Image, you cannot use it in two places like this. You can create the image as a separate resource with x:Shared= false and reference it in the style then a new one will be created in every place the style is used.


e.g.

<UserControl>
    <UserControl.Resources>
        <Image x:Key="img" x:Shared="false" Source="D:\Temp\dictionary16.png" />
        <Style x:Key="TestStyle" TargetType="{x:Type Button}">
            <Setter Property="Content" Value="{StaticResource img}" />
        </Style>
    </UserControl.Resources>
    <StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
        <Button Style="{StaticResource TestStyle}" />
        <Button Style="{StaticResource TestStyle}" />
    </StackPanel>
</UserControl>
like image 172
H.B. Avatar answered Oct 19 '22 16:10

H.B.


Already yesterday i found a user with a similar problem: WPF - Change a button's content in a style?

This post got me to this soloution (couldn't post it because of 8 hour limit of stackoverflow -.-)

<Setter Property="ContentTemplate">
    <Setter.Value>
        <DataTemplate>
            <Image Source="{mcWPF:LangRes imgSettings16, Bitmap}" Height="14"/>
        </DataTemplate>
    </Setter.Value>
</Setter>

Don't know weather this is more clean/dirty/better than H.B.'s soloution

like image 20
Reini Avatar answered Oct 19 '22 16:10

Reini