Reputation: 581
I have the following code which handles mouse drag event thrown by the thumb control. It works fine on standard code behind such as SettingView.xaml and SettingView.xaml.cs
but how do i handle this in my SettingViewModel.cs file.
So far i was able to wire the clicks using DelegateCommand(or RelayCommand) which takes the parameter, but how do i get the inputs from parameters that are sent by the events ? For instance drag event provides event args e.HorizontalChange and e.VerticalChange. Please have a look that the prototype of my code below.
Any elegant solution is much appreciated.
Thanks in advance.
================================================================================== SettingView.xaml
Thumb Name="thumbWest" DragDelta="thumbWest_DragDelta
SettingView.xaml.cs
private void thumbWest_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
_captureMargin.Left = _captureMargin.Left + e.HorizontalChange;
if (e.HorizontalChange < 0)
{
// Drag towards West
_widthRect = _widthRect + Math.Abs(e.HorizontalChange);
}
if (e.HorizontalChange > 0)
{
// Drag towards East
_widthRect = _widthRect - e.HorizontalChange;
}
Upvotes: 1
Views: 2615
Reputation: 3139
MVVM talks about getting rid of the code behind by directly binding a Command declared in ViewModel to the View. This works good for controls like Button which have ICommand property where you can bind the command. But in all other situations when the control does not expose an ICommand or if we want specific behavior on perticualr events, I use one of these 2 approaches:
1 - If I want a simple approach, I define an event handler and call the ViewModel command (RelayCommand) from event handler which specific param. In your case the code will look like this -
private void thumbWest_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
viewModel.DoSomthingCommand.Execute(new DoSomethingCommandParam(e.HorizontalChange))
}
Although we are adding code to code behind here I feel it is fine since we did not add any UI logic in the even handler. It is only executing the Command in ViewModel with proper params.
2 - If I am totally against putting any code in code behind, I will create an Attached Behavior to handle Drag and Drop and attached it to the control. Then call the ViewModel Command from the Attached Behavior. You can find a nice tutorial about using Attached Behavior here
Upvotes: 1