Passing two command parameters using a WPF binding Passing two command parameters using a WPF binding wpf wpf

Passing two command parameters using a WPF binding


Firstly, if you're doing MVVM you would typically have this information available to your VM via separate properties bound from the view. That saves you having to pass any parameters at all to your commands.

However, you could also multi-bind and use a converter to create the parameters:

<Button Content="Zoom" Command="{Binding MyViewModel.ZoomCommand">    <Button.CommandParameter>        <MultiBinding Converter="{StaticResource YourConverter}">             <Binding Path="Width" ElementName="MyCanvas"/>             <Binding Path="Height" ElementName="MyCanvas"/>        </MultiBinding>    </Button.CommandParameter></Button>

In your converter:

public class YourConverter : IMultiValueConverter{    public object Convert(object[] values, ...)    {        return values.Clone();    }    ...}

Then, in your command execution logic:

public void OnExecute(object parameter){    var values = (object[])parameter;    var width = (double)values[0];    var height = (double)values[1];}


In the converter of the chosen solution, you should add values.Clone() otherwise the parameters in the command end null

public class YourConverter : IMultiValueConverter{    public object Convert(object[] values, ...)    {        return values.Clone();    }    ...}


Use Tuple in Converter, and in OnExecute, cast the parameter object back to Tuple.

public class YourConverter : IMultiValueConverter {          public object Convert(object[] values, ...)         {           Tuple<string, string> tuple = new Tuple<string, string>(            (string)values[0], (string)values[1]);        return (object)tuple;    }      } // ...public void OnExecute(object parameter) {    var param = (Tuple<string, string>) parameter;}