How to change Border Background image programmatically

shnaz picture shnaz · Jun 16, 2013 · Viewed 7.4k times · Source

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

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

    <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?

I have tried but no success.

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

Thanks in advance

Shafi

Answer

Clemens picture Clemens · Jun 16, 2013

Assign a Name to the 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 Background property to type ImageBrush:

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