1

I have a UserControl say Stock and it has a Button called Display

<Button Command="{Binding DisplayCommand}" CommandParameter="StockGroups">Display</Button>

Now when i Click this button it should add an another UserControl named Display to the Canvas which is in HomeWindow and should pass the CommandParameter to the Display userControl.

private DelegateCommand<string> _displayCommand;        
public virtual void DisplayExecuted(string param){}
public ICommand DisplayCommand
{
    get
    {
        if (_displayCommand == null)
            _displayCommand = new DelegateCommand<string>(new Action<string>(DisplayExecuted));
        return _displayCommand;
    }            
}
Kishore Kumar
  • 12,675
  • 27
  • 97
  • 154

2 Answers2

2

An alternative method which is more MVVM-ish would be to have a boolean property named ShouldDisplayControl, which is then bound to the control's Visibility property (using the [BooleanToVisibilityConverter]) 1), while passing the CommandParameter as a second property, maybe ControlParameter, which the control is also bound to.

Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63
0

This is not an operation that should involve the ViewModel, since it does not manipulate any model data.

Instead of a ViewModel command, consider merely handling the button's OnClick in the code-behind of the xaml.

In your HomeWindow.xaml.cs file:

protected override void Display_OnClick(object sender, EventArgs e) {
    var buttonName = ((Button)sender).Name; // gets the name of the button that triggered this event
    var displayControl = new DisplayControl(); // your user control
    displayControl.param = buttonName; // set the desired property on your display control to the name of the button that was clicked
    ((Canvas)Content).Children.Add(displayControl); // 'Content' is your Canvas element
}

And in your HomeWindow.xaml file:

<Button x:Name="StockGroups" Click="Display_OnClick" Text="Display" />

That should get you what you want, without needing to create and invoke a command in the viewmodel. The name of the clicked button will be set to the specified property in your userControl, and an instance of the control will be created inside the Canvas.

Uchendu Nwachuku
  • 442
  • 3
  • 13