wpf 如何用图片设置矩形的背景?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17107720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:00:28  来源:igfitidea点击:

How to set the background of Rectangle with a picture?

c#wpfbackground

提问by Bubble

I create a Rectangle

我创建一个矩形

public void Set(Rectangle maps, int y, int x) {
    Map.Children.Add(maps);
    maps.SetValue(Grid.RowProperty, x);
    maps.SetValue(Grid.ColumnProperty, y);

}

But How to change the background with "Resources/1.jpg"?

但是如何使用“Resources/1.jpg”更改背景?

回答by Jonny Piazzi

Like this:

像这样:

<Rectangle>
    <Rectangle.Fill>
        <ImageBrush ImageSource="/YourAppName;component/Resources/1.jpg" />
    </Rectangle.Fill>
</Rectangle>

EDITED AGAIN (Sorry)

再次编辑(对不起)

Or in C#

或者在 C# 中

maps.Fill = new ImageBrush {
    ImageSource = new BitmapImage(new Uri(@"pack://application:,,,/YourAppName;component/Resources/1.jpg", UriKind.Absolute))
};

回答by NIPRUT

I was having trouble using the "/YourAppName;" portion of the address as suggested by @Jonny Piazzi. It probably works, I just couldn't get it to. Alternatively, I was able to make this method work.

我在使用“/YourAppName;”时遇到问题 @Jonny Piazzi 建议的地址的一部分。它可能有效,我只是无法做到。或者,我能够使这种方法起作用。

1) I added the image to my project in a folder I created: Images > Backgrounds > JellyFishBackground.jpg

1)我将图像添加到我创建的文件夹中的项目中:图像>背景> JellyFishBackground.jpg

2) I right clicked the image in Solution Explorer > Properties > Set Build Action to Resource

2)我右键单击解决方案资源管理器>属性>将构建操作设置为资源中的图像

3) Build project

3) 构建项目

4) Simply target the image as such: (in my case I targeted a row of my grid, and used a Stretch property, which are beyond the scope of this question, just fyi to avoid confusion)

4)简单地将图像定位为:(在我的情况下,我定位了我的网格的一行,并使用了 Stretch 属性,这超出了这个问题的范围,仅供参考以避免混淆)

<Rectangle Grid.Row ="0">
    <Rectangle.Fill>
        <ImageBrush ImageSource="/Images/Backgrounds/JellyFishBackground.jpg" Stretch="UniformToFill"/>
    </Rectangle.Fill>
</Rectangle>