2014-02-07 69 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

相關問題