wpf 如何以编程方式更改边框背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17136655/
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:01:11  来源:igfitidea点击:

How to change Border Background image programmatically

wpfborderimagebrush

提问by shnaz

I am creating a media player app in WPF c#. I am using Media Element to do this.

我正在 WPF c# 中创建一个媒体播放器应用程序。我正在使用媒体元素来做到这一点。

Anyways, I have used <Border> </Border>to add border some places.

无论如何,我已经习惯<Border> </Border>在某些地方添加边框。

    <Border Name="hej1">
                <Border.Background>
                    <ImageBrush ImageSource="Images\music.png"  Stretch="None"/>
                </Border.Background>

                <MediaElement ..../> 
    </Border>

I want to change the ImageSource to some other picture programmatically, how to do that?

我想以编程方式将 ImageSource 更改为其他图片,该怎么做?

I have tried but no success.

我试过但没有成功。

So for every song the image in <ImageBrush ImageSource="Images\music.png"is changed.

因此,对于每首歌曲,其中的图像<ImageBrush ImageSource="Images\music.png"都会发生变化。

Thanks in advance

提前致谢

Shafi

沙菲

回答by Clemens

Assign a Name to the ImageBrush:

为 ImageBrush 指定一个名称:

<ImageBrush x:Name="imageBrush" ImageSource="Images\music.png" Stretch="None"/>

Then use the named member in code:

然后在代码中使用命名成员:

var filename = @"Images\title.png";
imageBrush.ImageSource = new BitmapImage(new Uri(filename, UriKind.Relative));


Or simply cast the value of the Border's Backgroundproperty to type ImageBrush:

或者简单地将 BorderBackground属性的值转换为ImageBrush 类型:

var imageBrush = (ImageBrush)hej1.Background;
var filename = @"Images\title.png";
imageBrush.ImageSource = new BitmapImage(new Uri(filename, UriKind.Relative));

回答by Prashant vishwakarma

BitmapImage img = new BitmapImage(new Uri(@"Images\myimage.png"));
ImageBrush image = new ImageBrush();
image.ImageSource = img;
Border.Background =image;