I am having some repeating code in views, that are part of drag&drop operations. I have an ICommand on ViewModelBase that handles required operations on model for drag&drop operation. Since I was trying to avoid passing UI event arguments to ViewModel, I needed to make my own argument type that would be passed to DropCommand. So basically my code in View’s code behind looks like this:
// get data required for ordering operation
var args = MyHelperClass.OnDropCompleted(a); // where a is an argument from UI drop event
// execute command
if (args != null) ViewModel.DropCommand.Execute(args);
This works fine, however, this code is repeated on each view. My idea is to add a DropCommand to my custom UI control, so I could assign a ICommand binding in xaml
DropCommand={Binding DropSommand} <-- binds to ViewModel's DropCommand
Now, I could handle drop event in my custom UI control, and invoke a command on viewmodel and pass it calculated argument.
Problems:
1) I would like to subscribe to Drop operation only if DropCommand’s binding is set in xaml. How can i Check if this binding is set?
2) After I have created the argument to be passed to ViewModel’s ICommand, I would like to invoke this command from code. How can I do this?
Edit: I also have the following binding scenario:
DropCommand={Binding DataContext.DropCommand, elementName=window}
Within your drop event handler in your custom control’s codebehind:
The presence of a
BindingExpressiontells you that something is bound, and you can get to theSourceof that binding through theBindingExpression‘sParentBindingproperty.