ICommand Dependency Property

Xanagandr picture Xanagandr · Feb 21, 2015 · Viewed 11.6k times · Source

I have an UserControl with a button inside. This button needs to add some items to a Grid that's inside said UC. I'm aware I can do this with a Click event.

The issue here is I am using MVVM and altering data outside their corresponding ViewModel would break the format (So to say).

Is there a way to create an ICommand Dependency Property so I can bind said DP to the button and have the functionality of adding the item to the Grid in my ViewModel? (I already have the List in both my UC and my ViewModel and they are working as expected)

Thank you.

Answer

Xanagandr picture Xanagandr · Feb 22, 2015

Found a way to solve it in the way I was trying to. Leaving the answer here so people may use it:

1) In your User Control's code-behind, create a Dependency Property. I choose ICommand, since in my ViewModel I set it as a DelegateCommmand:

public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register(
        "Command",
        typeof(ICommand),
        typeof(UserControl));

    public ICommand Command
    {
        get 
        { 
            return (ICommand)GetValue(CommandProperty); 
        }

        set 
        { 
            SetValue(CommandProperty, value); 
        }
    }

2) In your UserControl's XAML code, bind this Dependency Property (In this case, a button):

<Grid DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}">

    <Button Command="{Binding Command}" />

</Grid>

3) Next, on your ViewModel, declare a Command property and configure accordingly:

public ICommand ViewModelCommand { get; set; }

public ViewModelConstructor()
{
    ViewModelCommand = new DelegateCommand(ViewModelCommandExecute);
}

private void ViewModelCommandExecute()
{
    // Do something
}

4) Finally, on your View where the UserControl is nested, we declare the binding:

<UserControls:UserControl Command={Binding ViewModelCommand}/>

This way, the binding will take place and you can bind Commands from the buttons of any User Control to your ViewModels without breaking MVVM.