如何使用multibinding将参数传递给命令?

nik*_*owj 3 wpf mvvm-toolkit

我正在使用MVVM工具包版本1.我有两个文本框textbox1和textbox2.我需要在按下按钮时将这两个值作为参数传递,并且需要在名为textbox3的第三个文本框上显示结果.

我的VM代码与此类似

public ICommand AddCommand
    {
        get
        {
            if (addCommand == null)
            {
                addCommand = new DelegateCommand<object>(CommandExecute,CanCommandExecute);
            }
            return addCommand;
        }
    }

    private void  CommandExecute(object parameter)
    {
        var values = (object[])parameter;
        var a= (int)values[0];
        var b= (int)values[1];
        Calculater calcu = new Calcu();
        int c = calcu.sum(a, b);      
    }

    private bool  CanCommandExecute(object parameter)
    {
        return true;  
    }
Run Code Online (Sandbox Code Playgroud)

当用户单击按钮但我的参数参数没有任何值时,将调用commandExecute方法.我如何将用户的值作为参数传递?并将结果返回到texbox3?

bli*_*eis 13

你可以使用Multibinding和转换器

<Button Content="Add" Command="{Binding AddCommand}"
 <Button.CommandParameter>
    <MultiBinding Converter="{StaticResource YourConverter}">
         <Binding Path="Text" ElementName="txt1"/>
         <Binding Path="Text" ElementName="txt2"/>
    </MultiBinding>
 </Button.CommandParameter>
</Button>
Run Code Online (Sandbox Code Playgroud)

变流器

public class YourConverter : IMultiValueConverter
{
 public object Convert(object[] values, ...)
 {
    //.Net4.0
    return new Tuple<int, int>((int)values[0], (int)values[1]);

    //.Net < 4.0
    //return values.ToArray();
 }

 ...
}
Run Code Online (Sandbox Code Playgroud)

命令

private void  CommandExecute(object parameter)
{
    var o= (Tuple<int, int>)parameter;
    var a= o.Item1;
    var b= o.Item2;
    Calculater calcu = new Calcu();
    int c = calcu.sum(a, b);      
}
Run Code Online (Sandbox Code Playgroud)

ps:请检查我的语法 - 它是从我的脑海里写的......