I want to put some functionality of my WPF app into user controls, mainly to reduce the clutter in my main window.
At the moment I have the following commands defined in my main window. These are consumed by ToolBar items and also menu items…
<Window.CommandBindings>
<CommandBinding Command="Close" Executed="CloseCommandHandler" />
<CommandBinding Command="local:AppCommands.OpenAttributes" Executed="OpenAttributesHandler" CanExecute="OpenAttributesCanExecute" />
</Window.CommandBindings>
Is there a way I can consume these same commands from a user control nested inside my main window?
Yes, through binding:
If it’s a user control, just make it expose a dependency property of type
ICommand. Also, MyCommand must be inside the ViewModel.EDIT:
Say you have a
Buttonnested within your UserControl:In the code behind of the user control, you need to expose “NestedCommand” as a dependency property:
Set “MyDefaultValue” to null, and “MyUserControlClassName” to the name of your UserControl, let’s call it Bob for a minute.
Now when you will use that UserControl, it will expose a NestedCommand property:
“my” is the xmlns namespace where your UserControls are defined, of course.
And MyCommand must be defined in your ViewModel a.k.a the object you put as DataContext of your view.
You can find out about it all over the web, but it boils down to creating a class that implements
INotifyPropertyChanged, adding anICommandto it, and then in the Window’s constructor: