How do I update an Image Source without losing the ability to refresh the image?

StackOverflow https://stackoverflow.com/questions/21622855

  •  08-10-2022
  •  | 
  •  

문제

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();
도움이 되었습니까?

해결책 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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top