Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
966 views
in Technique[技术] by (71.8m points)

wpf - 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:Tempdictionary16.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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:Tempdictionary16.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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...