简体   繁体   English

如何在不失去刷新图像能力的情况下更新图像源?

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

If I execute the following C#/WPF code, tempImage (System.Windows.Controls.Image) will show an image as expected. 如果执行以下C#/ WPF代码,则tempImage(System.Windows.Controls.Image)将按预期显示图像。

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 (ie, the original image is still shown instead of the updated image). 但是,如果我使用相同类型的新ImageSource对象更新LayerImageSource,则tempImage不会自行刷新(即,仍显示原始图像而不是更新的图像)。

I have tried setting the binding as shown below, but all I get is a black rectangle (before I even try to update LayerImageSource). 我尝试按如下所示设置绑定,但是我得到的只是一个黑色矩形(甚至在尝试更新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: 这是我的更新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();

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 参考链接

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. 不需要GetBindingExpression和UpdateSource代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM