Fritz45
Fritz45

Reputation: 782

How to set border background imagebrush in code-behind

I have a WPF custom user control that is used in a Windows Application. The control has a border as the main element, and this border has a default background image. The code below shows how this image is set as a default. The default image is a resource element (Images/BlueRoad.jpg).

I want to be able to programmatically change the image of the border background using an image filename as string (e.g. "C:\Pictures\myCustomPic.bmp"). I need to do this in code-behind using Visual Basic, unless there is a VERY simple way to do it in XAML. Either way, the picture will load in the startup code for the control.

I do not know much about WPF and this is just a small element of the application, so want to get this done as simply and quickly as possible.

Many Thanks!

<Border Name="mainBorder" Opacity="1" BorderBrush="SteelBlue" BorderThickness="3">
    <Border.Background>
        <ImageBrush  ImageSource="Images/BlueRoad.jpg"></ImageBrush>
    </Border.Background>

     Grid and other stuff goes here...

 </Border> 

Upvotes: 0

Views: 2556

Answers (2)

Randall Deetz
Randall Deetz

Reputation: 524

using System;
using System.Windows.Media;
using System.Windows.Media.Imaging;
...
var imagePath = @"pack://application:,,,/MyProject;component/Resources/BorderImage.png";
ImageBrush brush = new ImageBrush(new BitmapImage(new Uri(imagePath, UriKind.Absolute)));
MyBorder.Background = brush;

Upvotes: 1

ali kiani
ali kiani

Reputation: 887

you can use ImageBrush and BitmapImage to set brush to border background first you create BitmapImage with uri and send this BitmapImage to ImageBrush and assign ImageBrush to border background

Upvotes: 0

Related Questions