-2

My image is 20x20 pixels and when it's loaded it stretchs to fill the space of the grid which is WxH. When I click on the image I collect the mouse locations. Later I use them to draw the dots on the 20x20 image and save it to the file. But, because the image was stretched, I need to map the mouse location on WxH image to my original 20x20 image.

What is the proper way to do this in MVVM? My thoughts are:

  1. Bind to the ActualWidth and ActualHeight of the image and then calculate the ratio between the original image and the stretched image.
  2. Bind to the ScaleX and ScaleY of ScaleTransform of the image. But, it always returns 1 for ScaleX and ScaleY.

XAML

<Grid>
    <Image Source="{Binding MyImage}" Stretch="Fill">
         <Image.RenderTransform>
            <ScaleTransform ScaleX="{Binding ScaleX, Mode=OneWayToSource}" ScaleY="{Binding ScaleY, Mode=OneWayToSource}" />
        </Image.RenderTransform>
    </Image>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseLeftButtonDown">
            <cmd:EventToCommand Command="{Binding GetMouseLocationCommand}" PassEventArgsToCommand="True" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Grid>

CODE

public class VM
{
    public double ScaleX { get; set; }
    public double ScaleY { get; set; }
}
theateist
  • 13,879
  • 17
  • 69
  • 109

1 Answers1

0

You should bind to the ActualWidth and ActualHeight of the Image and then calculate the ratio between the original image and the stretched image.

Since these are read-only properties it requires some effort. Please refer to the following link for more information:

Pushing read-only GUI properties back into ViewModel

These properties will be set when the Image is stretched. The ScaleX and ScaleY properties of the ScaleTransform will not.

Community
  • 1
  • 1
mm8
  • 163,881
  • 10
  • 57
  • 88
  • @Why `ScaleX` and `ScaleY` properties of the `ScaleTransform` will not be set? When the image stretches, doesn't it change its scale? – theateist May 23 '17 at 14:29
  • No. At least not *that* scale. – mm8 May 23 '17 at 14:30
  • Can you explain more or give a relevant article? I haven't found something that will explain what happenes when it stretches. – theateist May 24 '17 at 03:38
  • Did you even bother to read my answer? You should use the ActualWidth and ActualHeight properties...Your original question was "What is the proper way to do this in MVVM?" and this has been answered. – mm8 May 24 '17 at 06:42