Let's try to show an example
public partial class MyUserControl : UserControl { ... public ICommand MyCommand { get { return (ICommand)GetValue(MyCommandProperty); } set { SetValue(MyCommandProperty, value); } } public static readonly DependencyProperty MyCommandProperty = DependencyProperty.Register("MyCommand", typeof(ICommand), typeof(MyUserControl)); ... }
Here we in our control declared the command, and what we described it as DependencyProperty will give us the opportunity to bind the command from the ViewModel to it, for example.
Now at the right moment we need to run it. Let this moment be the loading event of the control. We add to the code above
private void MyUserControl_Loaded(object sender, RoutedEventArgs e) { MyCommand?.Execute(/*Тут указывается параметр для команды, можно null*/); }
On the control side, we are done. Now we will connect our team with real action. In the ViewModel we describe a command that simply displays a MessageBox . As an ICommand implementation, I most often use the RelayCommand from MvvmLight .
public RelayCommand ShowMessageCommand { get; private set; } private void ShowMessage() { MessageBox.Show("Hello!"); }
And in the constructor ViewModel initialize
ShowMessageCommand = new RelayCommand (ShowMessage);
Now, for example, in the window, in which DataContext an instance of our ViewModel is installed we describe the following
<local:MyUserControl ... MyCommand={Binding Path=ShowMessageCommand}/>
Now when you call MyCommand?.Execute function will be ShowMessage . To complete the picture is not enough use of the parameters. But there is nothing difficult there. If you still do not understand yourself - ask.
UPDATE
In order for the control to bind a button to MyCommand , simply bind the Button.Command property to MyCommand . Thus, when you click on the button, the necessary command will be executed. But to do so
Т.е. в самом приложении, я уже не прописываю выполнение хранимых процедур, это все уже есть в UserContorol
Absolutely wrong. Controls should not take on such functionality