【问题标题】:How can I change WPF Button Image in Setter如何在 Setter 中更改 WPF 按钮图像
【发布时间】:2013-09-05 17:33:03
【问题描述】:

我在尝试更改 WPF (c#) 中按钮的控件模板时遇到了一个非常奇怪的问题。

我现在有以下代码:

    <Window.Resources>
    <Style x:Key="ButtonFocusVisual">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate>
                    <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="Black" StrokeThickness="1" StrokeDashArray="1 2"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style x:Key="MacOSX-Close" TargetType="{x:Type Button}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border Background="Black" BorderThickness="0">
                    <Image x:Name="bgimg" Source="bin/debug/Ressources/Images/GUI/frame-btn-defaulted.png"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="#ADADAD"/>
                        </Trigger>
                        <Trigger Property="IsPressed" Value="true">
                            <Setter TargetName="bgimg" Property="Source" Value="bin/debug/Ressources/Images/GUI/frame-btn-defaulted.png"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

所以这行不通。它说

    "{DependencyProperty.UnsetValue}" is no valid value for property "System.Windows.Controls.Image.Source" on a setter.

当我尝试在一个网格中使用多个图像(因为你只能设置一个孩子)并修改“可见性”属性时,按钮根本没有出现!!!没有按钮,没有图像。而且,是的,我确信图像存在。 但是源是相对于解决方案根的,而不是相对于编译的程序......这有关系吗?请帮帮我:)我有点绝望了……:(

最好的问候 ;) 如果您有不清楚的地方,请询问。

【问题讨论】:

  • Image.Source 是位图图像,而不是字符串。使用转换器并让它根据文件名创建位图并绑定到该位图。
  • 你确定吗?当我提供路径时,IDE 确实会显示图像!只是它似乎找不到位置,因为在开发过程中路径必须相对于 XAML 文件,但在运行时路径必须相对于 *.exe 启动位置。但是,如果要使用转换器……我将如何绑定它?我试了一个,好像没找到……
  • @PoweredByOrange 请注意,WPF 具有从 stringImageSource 的内置类型转换。在 XAML 中将 URL 字符串(例如相对文件名)应用于图像的 Source 属性是完全有效的。
  • @Clemens 你是对的......在我真正尝试之前忘记了这一点。

标签: c# wpf xaml wpf-controls controltemplate


【解决方案1】:

在你的项目中创建像资源这样的文件夹,并将图像放在你的资源文件夹中,它们的构建操作应该设置为资源。然后可以设置 Source = "/Resources/frame-btn-defaulted.png"

【讨论】:

  • “在您的项目中创建文件夹'xyz'”到底是什么意思?我应该把它放在解决方案根文件夹中还是应该把它放在'bin/debug/'中?问题是(在运行时)程序用尽了 /bin/debug/ 文件夹,但 xaml 文件位于更高的两个级别,因此程序没有机会在运行时访问该文件......好吧,我没有不希望像必须导航到 C:\ 级别以使用 xaml 文件中的相对路径...
  • 将其放入项目文件夹中,并确保在将图像添加到该文件夹​​后,应将图像的构建操作设置为资源。它会起作用的。
猜你喜欢
  • 2013-11-28
  • 1970-01-01
  • 1970-01-01
  • 2016-07-12
  • 2019-06-02
  • 1970-01-01
  • 1970-01-01
  • 2020-06-14
  • 1970-01-01
相关资源
最近更新 更多