How to pass MouseEvent and UIControl as two parameters when using MVVM?

72 views Asked by At

I'm changing a picture viewer project to MVVM, the XAML code is below.

<ScrollViewer Name="scrollViewer" HorizontalScrollBarVisibility="Visible">

   <Grid Name="Mygrid" Width="400" Height="490" HorizontalAlignment="Stretch" >
       <Grid.LayoutTransform>
           <TransformGroup x:Name="TfGroup">
                <ScaleTransform x:Name="MyscaleTransform"/>
            </TransformGroup>
        </Grid.LayoutTransform>

   <Border x:Name="imgborder" HorizontalAlignment="Center" VerticalAlignment="Center">
     <Image x:Name="Myimg" />
   </Border>
 
   <Canvas x:Name="canvas" Background="Transparent"/>

  </Grid>
</ScrollViewer>

The original code is as follows (MVVM is not used):

private void OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
    lastMousePositionOnTarget = Mouse.GetPosition(Mygrid);

    System.Windows.Point centerPoint = e.GetPosition(Myimg);

    var val = e.Delta * 0.01;

    if (MyscaleTransform.ScaleX + val < 0.1) return;
    if (MyscaleTransform.ScaleX + val > 100) return;

    MyscaleTransform.CenterX = centerPoint.X;
    MyscaleTransform.CenterY = centerPoint.Y;

    MyscaleTransform.ScaleX += val;
    MyscaleTransform.ScaleY += val;

}

I try to use MVVM and add the following code in XAML:

<i:Interaction.Triggers>
  <i:EventTrigger EventName="PreviewMouseWheel">
     <i:InvokeCommandAction Command="{Binding TestCommand}" PassEventArgsToCommand="True"/>
  </i:EventTrigger>
</i:Interaction.Triggers>

Now the problem arises, in the past code, I accessed the UIControls like 'Mygrid','Myimg' and so on, now, in the ViewModel, if the mouse event is received, I cannot receive the UIControls as parameters at the same time,

[RelayCommand]
private void Test(MouseWheelEventArgs e)
{
    //How to receive UIControls 'Mygrid' ,'Myimg' as parameters?
    lastMousePositionOnTarget = Mouse.GetPosition(Mygrid);

    System.Windows.Point centerPoint = e.GetPosition(Myimg);
}

I have searched related posts, but did not find relevant answers. Most of them discussed how to pass multiple parameters. I did not see passing mouse events and parameters at the same time, or they used the older MVVMLight, which is now outdated.

So, if I use CommunityToolkit.Mvvm, how can I achieve the above function?

Thanks

0

There are 0 answers