Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
832 views
in Technique[技术] by (71.8m points)

wpf - How to pass parameters to command using multibinding?

I am using MVVM tool kit version1. I have two Text boxes textbox1 and textbox2. I need to pass these two values as parameter when pressing on button and need to show the result on a third Text Box named textbox3.

my VM code similar like this

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;  
    }

The commandExecute method is called when the user click on the button but my the parameter argument doesn't not have any value. how i can pass the user's values as parameter?. and return the result to the texbox3?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can use Multibinding and a Converter

<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>

converter

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();
 }

 ...
}

command

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);      
}

ps: pls check my syntax - its written from my mind...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...