【问题标题】:Set an image as a Button's content in style在样式中将图像设置为按钮的内容
【发布时间】:2011-11-07 05:17:04
【问题描述】:

我有一个这样定义的 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”的图像?

谢谢。

【问题讨论】:

    标签: wpf xaml datatemplate staticresource


    【解决方案1】:

    您不能使用将 Content 属性设置为 Image 控件的实例,因为这样图像可能被多个按钮使用。这将导致“视觉对象已经是另一个视觉对象的子对象”异常。

    相反,您可以像这样使用 DataTemplate:

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

    显然您可能需要调整图像的源 URI。

    【讨论】:

    • 这立即帮助了我 - 我有一个“视觉已经是......”异常,我将路径设置为样式中的按钮内容。谢谢。
    【解决方案2】:

    在我的应用程序中,我定义了一个 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>
    

    但在您的情况下,如果您想对所有 Button 对象使用相同的图像并设置特定的Style,您可以简单地在Template 中使用&lt;Image Source="pack://application:,,,/My.Assembly.Name;component/Icons/revert.png" /&gt;,如果您想使用图像已作为资源包含在应用程序中。

    【讨论】:

    • 谢谢,但效果不是很好。请参阅 CodeNaked 的帖子。
    • 对不起,我说错了。应该是 ContentTemplate (如我发布的代码转储中),而不是我原始摘要中的 Content。已为未来的观众编辑。
    猜你喜欢
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 2011-02-15
    • 1970-01-01
    • 2012-07-14
    • 2014-11-09
    相关资源
    最近更新 更多