Execute a usercontrol command from a viewmodel
I have a usercontrol with a command, what I would like to do is execute this command from the containing view's ViewModel.
This would be easy to accomplish in the code behind, as I could just go "UserControl.MyCommand.Execute", but of course I want to be able to do this in the ViewModel.
In theory, what I would like to do is bind the UserControl's Command to a Command on the ViewModel which I can execute and will then be h开发者_如何学JAVAandled by the UserControl. Something like this:
...
<local:MyControl
MyCommand="{Binding ViewModelsCommand}" />
...
Of course this will have the opposite affect to what I want to do, as now the ViewModelsCommand is bound to MyCommand. So how to invert this?
Basically I want to be able to bind something like this:
ViewModelsCommand="{Binding MyControl.MyCommand}"
Any ideas or inspiration would be welcomed, I can't see a binding Mode that would let me do this. And I'm not sure how to access the DataContext's properties for binding (usually you would do just bind and have twoway handle this, but of course that doesn't work in this scenario).
Thanks in advance.
You are instantiating the view-model in the constructor of the view.
Why not set the value explicitly upon construction?
public SomeView()
{
var viewModel = new SomeViewModel();
viewModel.ViewModelCommand = MyCommand; // or = myControl.MyCommand
DataContext = viewModel;
}
It is possible to use a binding with OneWayToSource
, TwoWay
, or Explicit
, but you still have to explicitly update source at least once in code (always if you use Explicit
).
myControl.GetBindingExpression(MyControl.MyCommandProperty).UpdateSource();
I use PRISM's EventAggregator, or MVVMLight's Messenger to allow two ViewModels to talk, but your case looks slightly different where you have a view(UserControl) talking to a ViewModel.
Please note, the following answer is not correct. It seems that OneWayToSource only updates after the target-property has changed. However I don't delete this answer to inform other people which are not aware of this behaviour (like me).
Old answer (see text above)
IMO your example should work (if MyControl.MyCommand is a public property that returns an ICommand). Have you tried the BindingMode OneWayToSource
?
<local:MyControl
MyCommand="{Binding ViewModelsCommand,Mode=OneWayToSource}" />
精彩评论