在样式中将图片设为按钮的内容

27

我有一个WPF按钮,定义如下:

<Button Style="{StaticResource RevertButtonStyle}" />

这是样式的展示:

<Style x:Key="RevertButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Height" Value="25" />
    <Setter Property="Width" Value="20" />
    <Setter Property="Margin" Value="3,0,0,0" />
</Style>

我该如何更改样式以指定使用名为"revert.png"的图像作为内容?

谢谢。

2个回答

45

如果将 Content 属性设置为 Image 控件的实例,则该图像可以被多个按钮使用。这会导致 "visual is already the child of another visual" 异常。

相反,您可以使用 DataTemplate,如下所示:

<Setter Property="ContentTemplate">
    <Setter.Value>
        <DataTemplate>
            <Image Source="revert.png" />
        </DataTemplate>
    </Setter.Value>
</Setter>

显然你可能需要调整图片的源URI。


这立即帮助了我 - 我在样式中设置为按钮内容的路径引发了“visual已经...”异常。谢谢。 - Pieter Müller

4
在我的应用程序中,我定义了一个ImageButton控件,它指定了一个ImageSource属性。
这是这样设计的:
<Style TargetType="{x:Type controls:ImageButton}">
    <Setter Property="ForceCursor" Value="True" />
    <Setter Property="Cursor" Value="Hand" />

    <Setter Property="ToolTip" Value="{Binding Path=Caption, RelativeSource={RelativeSource Mode=Self}}" />

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type controls:ImageButton}">
                <Image Width="16" Height="16" Source="{Binding Path=ImageSource, RelativeSource={RelativeSource Mode=TemplatedParent}}" Name="image" />

                <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter TargetName="image" Property="Opacity" Value="0.3" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

但是在你的情况下,如果你想要为所有具有特定 StyleButton 对象使用相同的图像,你可以简单地在 Template 中使用 <Image Source="pack://application:,,,/My.Assembly.Name;component/Icons/revert.png" />,如果你想要使用的图像已经作为资源包含在应用程序中。


谢谢,但效果不是很好。请看CodeNaked的帖子。 - sean717
抱歉,我说错了。应该是ContentTemplate(就像我发布的代码转储中一样),而不是原始摘要中的Content。已经进行了编辑以供未来查看者参考。 - fatty

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接