I managed to fix this issue by writing a MultiValueConverter
which takes in an image filepath and a pixel width (bound in xaml using a MultiBinding) and returns the correct size bitmap to display in the thumbnail Image control. The result is that the correct size image is used (and cached) so the ListBox
width is constant.
This is the code for the converter:
public class PathToThumbnailConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var path = values[0] as string;
var decodeWidth = (int)values[1];
if (!string.IsNullOrEmpty(path))
{
var info = new FileInfo(path);
if (info.Exists && info.Length > 0)
{
var bi = new BitmapImage();
bi.BeginInit();
bi.DecodePixelWidth = decodeWidth;
bi.CacheOption=BitmapCacheOption.OnLoad;
bi.UriSource=new Uri(info.FullName);
bi.EndInit();
return bi;
}
}
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
And here is the xaml for declaring it:
<Window.Resources>
<valueConverters:PathToThumbnailConverter x:Key="ThumbConverter"/>
</Window.Resources>
And using it:
<Image.Source>
<MultiBinding Converter="{StaticResource ThumbConverter}">
<Binding Path="ThumbnailPath"/>
<Binding RelativeSource="{RelativeSource FindAncestor,
AncestorType={x:Type Window}}" Path="DataContext.ThumbnailWidth"/>
</MultiBinding>
</Image.Source>