RelayCommand and CommandParameters

Oct 11, 2009 at 3:21 PM

I just started using the RelayCommand a couple of days ago and love it. But I seem to be stuck on how to use the CommandParameter with it.

<Button x:Name="btnPrint"
    Width="50"
    Height="50"
    HorizontalAlignment="Right"
    VerticalAlignment="Bottom"
    Command="{Binding Path=PrintCommand}"
    CommandParameter="{Binding ElementName=PrintLayout}"/>

public ICommand PrintCommand
{
    get
        {
            if (printCommand == null)
                printCommand = new RelayCommand(() => this.Print());
            return printCommand;
        }
}
The idea here is that the element that is passed through CommandParameter would be passed to the print function.

Oct 11, 2009 at 4:40 PM

Sorry for wasting anyones time, it took me about 30 minutes after posting the original to realize the error of my way.

Original

private RelayCommand printCommand;

Modified

private RelayCommand<object> printCommand;

public ICommand PrintCommand
{
    get
        {
            if (printCommand == null)
                printCommand = new RelayCommand<object>(
                    (param) => this.Print(param));
            return printCommand;
        }
}
Oct 21, 2009 at 8:59 AM

Assuming you're using the original RelayCommand class from this post: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

I think the correct syntax should be:

private RelayCommand printCommand;

public ICommand PrintCommand
{
    get
        {
            if (printCommand == null)
                printCommand = new RelayCommand(
                    (param) => this.Print(param));
            return printCommand;
        }
}