マスター/詳細ベースに画像を含む項目のリスト (単純な ListBox) があります (ユーザーがリスト項目をクリックすると、詳細ページが開きます)。ここ、ここ、ここ、およびここで説明されている、画像のメモリリークに関する非常に有名な問題に直面しました。
考えられる方法の 1 つは、NavigatingFrom 時にすべての画像を実行してそれらを消去することです。
スレッドの 1 つで、より興味深い解決策を見つけました。画像は自動的に消去されますが、仮想化では機能しません (ImageSource を格納するためのプライベート フィールドを追加すると、画像が失われるか混合されます)。提案された修正は、依存関係プロパティを追加することでした。
しかし、私はまだ同じ問題に直面しています。下にスクロールして上に戻った後、画像が混同されます。依存関係プロパティがランダムに変更されているように見えますが、変更されている瞬間を捉えることができません。
public class SafePicture : ContentControl
{
public static readonly DependencyProperty SafePathProperty =
DependencyProperty.RegisterAttached(
"SafePath",
typeof(string),
typeof(SafePicture),
new PropertyMetadata(OnSourceWithCustomRefererChanged));
public string SafePath
{
get { return (string)GetValue(SafePathProperty); }
set { SetValue(SafePathProperty, value); }
}
private static void OnSourceWithCustomRefererChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue == null) // New value here
return;
}
public SafePicture()
{
Content = new Image();
Loaded += OnLoaded;
Unloaded += OnUnloaded;
}
private void OnLoaded(object _sender, RoutedEventArgs _routedEventArgs)
{
var image = Content as Image;
if (image == null)
return;
var path = (string)GetValue(SafePathProperty); // Also, tried SafePath (debugger cant catch setter and getter calls), but same result.
image.Source = null;
{
var request = WebRequest.Create(path) as HttpWebRequest;
request.AllowReadStreamBuffering = true;
request.BeginGetResponse(result =>
{
try
{
Stream imageStream = request.EndGetResponse(result).GetResponseStream();
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
if (imageStream == null)
{
image.Source = new BitmapImage { UriSource = new Uri(path, UriKind.Relative) };
return;
}
var bitmapImage = new BitmapImage();
bitmapImage.CreateOptions = BitmapCreateOptions.BackgroundCreation;
bitmapImage.SetSource(imageStream);
image.Source = bitmapImage;
});
}
catch (WebException)
{
}
}, null);
}
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
var image = Content as Image;
if (image == null)
return;
var bitmapImage = image.Source as BitmapImage;
if (bitmapImage != null)
bitmapImage.UriSource = null;
image.Source = null;
}
}
使用法:
<wpExtensions:SafePicture SafePath="{Binding ImageUrl}"/>
そのため、一見問題なく動作しますが、下にスクロールして上に戻ると、画像がランダムに変更されます。
編集:この場合、今のところ、仮想化なしで純粋なListBoxのみを使用しています(ただし、他の場合は期待しています)。
EDIT2: この問題を再現するためのサンプル プロジェクト。しばらくすると解決策が含まれると思います: https://simca.codeplex.com/