Setting Button's Content to <Image> via Styles

♀尐吖头ヾ 提交于 2019-12-30 04:41:07

问题


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.


回答1:


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>



回答2:


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



来源:https://stackoverflow.com/questions/6356810/setting-buttons-content-to-image-via-styles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!