I'm trying to get the mouse position related to a wpf control (a Canvas in this case) using MVVM Framework with Prism Library.
I already got a solution but I'm not sure if it's a correct way to use the MVVM framework.
Main window:
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="250"/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" BorderBrush="Gray" BorderThickness="1">
<Canvas HorizontalAlignment="Center" VerticalAlignment="Center"
Width="{Binding CanvasWidth}" Height="{Binding CanvasHeight}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseMove">
<prism:InvokeCommandAction Command="{Binding MouseMove}"/>
</i:EventTrigger>
<i:EventTrigger EventName="Loaded">
<prism:InvokeCommandAction Command="{Binding Loaded}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Image Source="{Binding Image}" />
</Canvas>
</Border>
<TextBlock Grid.Column="1" Text="{Binding Text}"/>
<StackPanel Grid.Column="1">
<TextBlock Text="{Binding MouseX, StringFormat='X={0}'}" Grid.Column="1" />
<TextBlock Text="{Binding MouseY, StringFormat='Y={0}'}" Grid.Column="1" />
</StackPanel>
</Grid>
In this XAML code snippet the canvas has 2 Event triggers that I use for converting:
- the "MouseMove" event to give the XY pointer position
- and the "Loaded" event where the tricky part is. Here I pass the instance obj from Canvas to the controller through this EventTrigger, the in the controller I use this code:
Loaded and MouseMove commands definition:
public DelegateCommand<MouseEventArgs> MouseMove { get; private set; }
public DelegateCommand<RoutedEventArgs> Loaded { get; private set; }
Constructor:
public MainWindowViewModel()
{
MouseMove = new DelegateCommand<MouseEventArgs>(GetMousePosition);
Loaded = new DelegateCommand<RoutedEventArgs>(GetCanvas);
}
Properties definition:
private string _mouseX;
public string MouseX
{
get { return _mouseX; }
set { SetProperty(ref _mouseX, value); }
}
private string _mouseY;
public string MouseY
{
get { return _mouseY; }
set { SetProperty(ref _mouseY, value); }
}
private System.Windows.Controls.Canvas _canvas;
public System.Windows.Controls.Canvas Canvas
{
get { return _canvas; }
set { SetProperty(ref _canvas, value); }
}
Methods called by commands:
private void GetCanvas(RoutedEventArgs obj)
{
Canvas = (System.Windows.Controls.Canvas)obj.Source;
}
private void GetMousePosition(MouseEventArgs eventParam)
{
Point position = eventParam.GetPosition(Canvas);
MouseX = position.X.ToString();
MouseY = position.Y.ToString();
}
Is this way a correct usage? Even this working I feel like passing the Canvas obj to the controller I'm doing something like "code behind".