Since there is no mouse position property you can bind (for which you would use Mode=OneWayToSource
), you could listen to the MouseMove
event:
private void OnMouseMove(object sender, MouseEventArgs e)
{
myViewModel.MousePosition = e.GetPosition(this);
}
Before you say that's not MVVM because it uses code-behind, from http://msdn.microsoft.com/en-us/library/gg405484(v=pandp.40).aspx
In some cases, the code-behind may contain UI logic code that implements visual behavior that is difficult or inefficient to express in Extensible Application Markup Language (XAML), such as complex animations, or when the code needs to directly manipulate visual elements that are part of the view. You should not put any logic code in the view that you need to unit test. Typically, logic code in the view's code-behind will be tested via a UI automation testing approach.
As pointed out another method could be to use a CallMethodAction to bind event invocations to a call a method on your ViewModel:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity
xmlns:ei="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactions
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseMoved">
<ei:CallMethodAction TargetObject={Binding} MethodName="OnMouseMoved"/>
</i:EventTrigger>
</i:Interaction.Triggers>
However I prefer not to use a binding here as the event will be raised very frequently and a binding will involve more overhead.