Question

If I execute the following C#/WPF code, tempImage (System.Windows.Controls.Image) will show an image as expected.

Image tempImage = new Image();
tempImage.Source = layers[layerIndex].LayerImageSource;
// LayerImageSource is of type "ImageSource"

However, if I update LayerImageSource with a new ImageSource object of the same type, tempImage doesn't refresh itself (i.e., the original image is still shown instead of the updated image).

I have tried setting the binding as shown below, but all I get is a black rectangle (before I even try to update LayerImageSource).

Image tempImage = new Image();

Binding b = new Binding();
b.Path = new PropertyPath("BitmapSource"); // Also tried "Source" and "ImageSource"
b.Source = layers[layerIndex].LayerImageSource;
b.Mode = BindingMode.TwoWay; // Also tried BindingMode.Default
tempImage.SetBinding(Image.SourceProperty, b);

Here is my code to update LayerImageSource:

layerToUpdate.LayerImageSource = updatedMasterImage.ColoredImageSource;

Image curImage = (Image)curGrid.Children[0]; // Get the image from the grid
BindingExpression be = curImage.GetBindingExpression(Image.SourceProperty);
if (be != null)
    be.UpdateSource();
Was it helpful?

Solution 2

I figured out the problem. The source must refer to the object and the path must refer to the property of the source object to which the binding is being bound. The complete code is below.

            Binding tempSourceBinding = new Binding();
            tempSourceBinding.Source = layers[layerIndex].layerImage;
            tempSourceBinding.Path = new PropertyPath("Source");
            tempSourceBinding.Mode = BindingMode.TwoWay;

            Image tempImage = new Image();
            tempImage.SetBinding(Image.SourceProperty, tempSourceBinding);

            curGrid.Children.Insert(0, tempImage);

The GetBindingExpression and UpdateSource code is not necessary.

OTHER TIPS

Try this

Image tempImage = new Image();
BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = new Uri(layers[layerIndex].LayerImageSource.ToString(), UriKind.Relative);
img.EndInit();
tempImage.Source = img;

Reference link

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top