WPF Command handling in different user controls
I have two different user controls in my UI. These controls are siblings in the UI hierarchy. Is it possible to fire a command from one user control and handle it on the other?
In other words c开发者_如何学编程an I use the ICommand property from the following ViewModel from some other user control(say UserControlAViewModel )?
class UserControlBViewModel : ViewModelBase
{
public ICommand Command
{
get
{
if (_Command == null)
{
_Command = new RelayCommand(param => this.CommandExecute(), param => this.CommandCanExecute);
}
return _Command ;
}
}
}
Is this your scenario? You have a parent view with two controls (ChildViewA and ChildViewB). They each have their own VM:
ParentView - ParentVM ChildViewA - ChildAVM ChildViewB - ChildBVM
ChildViewA executes a command which is handled inside ChildAVM using RelayCommand. ChildAVM informs ParentVM that command is executed. ParentVM informs ChildBVM that command is executed. How the VMs communicate with each other depends on how loosely connected you need/want them to be.
One simple way of implementing this is to have the child VMs implement INotifyPropertyChanged. Then the ParentVM can subsribe to the PropertyChanged event. The command will cause some property to change on the ChildAVM which will be noticed by the ParentVM. The parentVM will next set some property on the ChildBVM.
In Silverlight, I would do something like the following. It should work in WPF also.
<Button x:Name="Btn01"
DataContext="{StaticResource Btn01ViewModel}"
Command="{Binding MyButtonCommand}"></Button>
<Button Command="{Binding DataContext.MyButtonCommand, ElementName=Btn01}"></Button>
精彩评论