I have an observablecollection of datatype ViewModel.
In my data template - I have a ListBox that is bound to the observable collection. I then have a datatemplate defined for each ListBoxItem. In that template, I have a button, whose ToolTip consists of a Grid that contains an image, whose source is bound to a converter that will generate a Bitmap image of the corresponding view model and return it. The converter derives from IMultiValueConverter, so I am passing in two values - the first value is a Thumbnail property from the view model, which initially should be null, and the second value I am passing in is the view model itself. Basically, the converter checks to see if the thumbnail property is null, and if it is, then it wraps the view model in a content presenter and then generates a bitmap from the content presenter and returns the image, which should then be set as the value of the thumbnail image of the view model, and displayed accordingly when the user moves their mouse over the button. Refer to the code below:
Here is the converter code:
RenderTargetBitmap bitmap = null;
if (values == null)
{
return null;
}
var thumbnail = values[0] as BitmapSource;
object viewModel = values[1];
if (thumbnail != null)
{
return thumbnail;
}
if (viewModel != null)
{
var contentControl = new ContentPresenter { DataContext=viewModel, Content = viewModel };
var viewBox = new Viewbox { Child = contentControl };
viewBox.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
viewBox.UpdateLayout();
bitmap = new RenderTargetBitmap((int)contentControl.DesiredSize.Width, (int)contentControl.DesiredSize.Width, 96, 96, PixelFormats.Pbgra32);
var drawingVisual = new DrawingVisual();
var drawingContext = drawingVisual.RenderOpen();
var visualBrush = new VisualBrush(contentControl);
using (drawingContext)
{
drawingContext.DrawRectangle(visualBrush, null, new Rect(new Point(0, 0), new Point(bitmap.PixelWidth, bitmap.PixelHeight)));
}
bitmap.Render(drawingVisual);
}
return bitmap;
And here is the XAML:
<Button.ToolTip>
<Grid>
<Image Width="Auto" Height="Auto">
<Image.Source>
<MultiBinding Converter="{StaticResource elementToImageConverter}" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding RelativeSource="{RelativeSource TemplatedParent}" Path="DataContext.Thumbnail" UpdateSourceTrigger="PropertyChanged" />
<Binding RelativeSource="{RelativeSource TemplatedParent}" Path="DataContext" UpdateSourceTrigger="PropertyChanged"/>
</MultiBinding>
</Image.Source>
</Image>
</Grid>
</Button.ToolTip>
I have stepped through the code etc. and everything is working as expected, except for two things:
(1) A blank image appears in the tooltip (2) The Thumbnail property never gets set for the corresponding ViewModel.
Any thoughts on what I am doing wrong? I'm almost open to a better solution, if you know of one.
Thanks.
Chris