2014-02-07 70 views
0

如果我执行下面的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

你究竟在哪里使用这个图像? 'PictureBox'? – Leron

+0

@Leron:这是一个WPF项目,因此该图像的类型为System.Windows.Controls.Image。为了清楚起见,我更新了主要问题和标签。 – nb1forxp

回答

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代码是没有必要的。

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

+0

不幸...只是一个黑色的矩形。任何其他想法? – nb1forxp

相关问题