Reputation: 3053
I have a Canvas
with some images (24x24 in size) on it and I also have a scrollbar that zooms in and out the canvas.
I would like to make the images stay the same size when resizing the canvas so I thought of binding the width / height of the images to the zoom value so that their width / height will be dependant of the zoom value (So, for example, they'll be Width = Width / ZoomValue
or something similar)
How can I obtain this behavior using WPF and binding?
Thanks!
Upvotes: 3
Views: 210
Reputation: 62246
Not very sure if there is somethign built-in done on this subject already in WPF 4.0
, also cause this feature was requested long years ago by users. The only valuable solution, imo, that you can apply is to assign your childcontrol.RenderTransform
to inverse of the transformation matrix
of its parent, so canvas
.
Let a databinding to assign correct value
By doing so, hope it's clear, you reset transformation applied to the canvas and get the "old" matrix. Considering that you're talking about a single transformation (there is no Translation
, Scale
and Rotation
made insequence) you have to get mathematically predictable (so correct) "original" matrix (they call it Identity
).
Look on this answer, which refers to another one again.
Hope this helps.
Upvotes: 1
Reputation: 16628
Assuming the images all have a width of 24, bind to ZoomValue and use an IValueConverter:
(ZoomValue has to be on your ViewModel)
<Image Source="..." Width="{Binding ZoomValue, Converter={StaticResource ZoomToWidthConverter}" />
And the IValueConverter:
public class ZoomToWidthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Double imgOriginalWidth = 24;
return imgOriginalWidth / System.Convert.ToDouble(value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Double imgOriginalWidth = 24;
return System.Convert.ToDouble(value) * imgOriginalWidth;
}
}
The Resources of the Canvas must hold a key for ZoomToWidthConverter:
<Canvas>
<Canvas.Resources>
<local:ZoomToWidthConverter x:Key="ZoomToWidthConverter " />
</Canvas.Resources>
</Canvas>
If the images can have different original width, use a MultiBinding along with an IMultiValueConverter.
Upvotes: 2
Reputation: 4676
Starting point is to define a converter that you'll use in binding, here are some links that can be useful:
Hope this helps!
Upvotes: 1