0

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> 
Dmitrii Lobanov
  • 4,897
  • 1
  • 33
  • 50
Fritz45
  • 752
  • 1
  • 10
  • 23

2 Answers2

1
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;
Randall Deetz
  • 512
  • 4
  • 25
0

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

ali kiani
  • 877
  • 1
  • 14
  • 29
  • Hi Ali Kiani - thanks for your comment and apologies for my late reply. The problem is I cannot seem to access this imagebrush in code. Also the image I want to set it to is a run-time loaded image and not a resource file. Like I said - I am not a WPF expert and was hoping some expert may just have a code snippet for me to solve the problem. Thanks again. – Fritz45 Dec 13 '11 at 20:05