开发者

Setting Button's Content to <Image> via Styles

开发者 https://www.devze.com 2023-03-13 07:28 出处:网络
Can\'t get this to work: <UserControl> <UserControl.Resources> <ResourceDictionary> <Style x:Key=\"TestStyle\" TargetType=\"{x:Type Button}\">

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.


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>


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

0

精彩评论

暂无评论...
验证码 换一张
取 消