wpfborderimagebrush

How to change Border Background image programmatically


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


Solution

  • 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));