如果我执行以下C#/ WPF代码,tempImage(System.Windows.Controls.Image)将按预期显示图像。
Image tempImage = new Image();
tempImage.Source = layers[layerIndex].LayerImageSource;
// LayerImageSource is of type "ImageSource"
但是,如果我使用相同类型的新ImageSource对象更新LayerImageSource,则tempImage不会自行刷新(即仍然显示原始图像而不是更新的图像)。
我已尝试设置绑定,如下所示,但我得到的只是一个黑色矩形(在我尝试更新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);
这是我更新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();
答案 0 :(得分:0)
试试这个
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;
参考link
答案 1 :(得分:0)
我弄明白了这个问题。源必须引用该对象,并且该路径必须引用绑定绑定到的源对象的属性。完整的代码如下。
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);
不需要GetBindingExpression和UpdateSource代码。