![](/img/trans.png)
[英]How can I set an Image.Source from a StorageFile without losing quality?
[英]How do I update an Image Source without losing the ability to refresh the image?
如果執行以下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();
嘗試這個
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;
參考鏈接
我解決了這個問題。 源必須引用對象,而路徑必須引用綁定所綁定到的源對象的屬性。 完整的代碼如下。
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代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.