【问题标题】:WPF set window background from image resourceWPF从图像资源设置窗口背景
【发布时间】:2017-12-14 12:40:39
【问题描述】:

我正在尝试从“资源”文件夹中的图像设置窗口背景:

<Window Background="{StaticResource MyImageBrush}">
<Window.Resources>
    <ImageBrush x:Key="MyImageBrush" ImageSource="/ApplicationName;component/Data/
        MyImage.jpg" />
</Window.Resources>

它编译正确,但是当 Visual Studio 在编译后刷新 xaml 视图时出现消息错误:

找不到静态资源引用“MyImageBrush”。

如果我删除窗口的背景属性,然后我编译,它编译正常,然后我再次输入背景属性并且它可以工作,但是当再次编译时显示上述消息错误。

如果可能,我如何从 xaml 设置窗口背景?

【问题讨论】:

  • 当您说“资源”文件夹时,它应该是 Pack URI 的一部分,例如ImageSource="/Resources/Data/MyImage.jpg"。也就是说,您不能在外部 &lt;Window&gt; 标记中引用来自 Window.Resources 的资源。将资源移至 App.xaml 中的 Application.Resources

标签: c# wpf xaml window


【解决方案1】:

您不需要声明资源。直接分配 Window 的 Background 属性:

<Window ...>
    <Window.Background>
        <ImageBrush ImageSource="/Data/MyImage.jpg"/>
    </Window.Background>
    ...
</Window>

【讨论】:

    【解决方案2】:

    要解决此问题,您可以将 ImageBrush 资源移动到 App.xaml

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-12
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      相关资源
      最近更新 更多