Let\'s imagine I have some user control. The user control has some child windows. And user control user wants to close child windows of some type. There is a method in user
Most answers to this question involve a state variable that is controlled by the ViewModel and the View acts on changes to this variable. This is good for stateful commands like opening or closing a window, or simply showing or hiding some controls. It doesn't work well for stateless event commands though. You could trigger some action on the rising edge of the signal but need to set the signal to low (false) again or it won't ever trigger again.
I have written an article about the ViewCommand pattern which solves this problem. It is basically the reverse direction of regular Commands that go from the View to the current ViewModel. It involves an interface that each ViewModel can implement to send commands to all currently connected Views. A View can be extended to register with each assigned ViewModel when its DataContext property changes. This registration adds the View to the list of Views in the ViewModel. Whenever the ViewModel needs to run a command in a View, it goes through all registered Views and runs the command on them if it exists. This makes use of reflection to find the ViewCommand methods in the View class, but so does Binding in the opposite direction.
The ViewCommand method in the View class:
public partial class TextItemView : UserControl
{
[ViewCommand]
public void FocusText()
{
MyTextBox.Focus();
}
}
This is called from a ViewModel:
private void OnAddText()
{
ViewCommandManager.Invoke("FocusText");
}
The article is available on my website and in an older version on CodeProject.
The included code (BSD licence) provides measures to allow renaming methods during code obfuscation.