如何使用多重绑定将参数传递给命令? [英] How to pass parameters to command using multibinding?
问题描述
我使用的是 MVVM 工具包版本 1.我有两个文本框 textbox1 和 textbox2.我需要在按下按钮时将这两个值作为参数传递,并且需要在名为 textbox3 的第三个文本框上显示结果.
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;
}
当用户单击按钮时会调用 commandExecute 方法,但我的参数参数没有任何值.我如何将用户的值作为参数传递?并将结果返回给 texbox3?
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?
推荐答案
你可以使用多重绑定和转换器
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>
转换器
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();
}
...
}
命令
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:请检查我的语法——它是我脑子里写的...
ps: pls check my syntax - its written from my mind...
这篇关于如何使用多重绑定将参数传递给命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!