我正在使用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;
}
当用户单击按钮但我的参数参数没有任何值时,将调用commandExecute方法。我如何将用户的值作为参数传递?并将结果返回到texbox3?
答案 0 :(得分:12)
您可以使用Multibinding和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:请检查我的语法 - 从我的脑海中写出......
答案 1 :(得分:1)
您可以在ViewModel中创建属性并将其绑定到您需要使用INotifyPropertyChanged通知更改的TextBox
....
public MyViewModel:INotifyPropertyChanged
{
private string1;
private string2;
private string3;
//Make a similar propety for string2 and string3
public string String1
{
get
{
return string1;
}
set
{
string1=value;
//Implementation of Propertychanged is left upon you
InvokePropertyChanged("String1");
}
}
public ICommand AddCommand
{
get
{
if (addCommand == null)
{
addCommand = new DelegateCommand<object>(CommandExecute,CanCommandExecute);
}
return addCommand;
}
}
private void CommandExecute(object parameter)
{
var a= String1;
var b= String2;
Calculater calcu = new Calcu();
String3 = (calcu.sum(a, b)).ToString();
}
private bool CanCommandExecute(object parameter)
{
return true;
}
}
<TextBox Text={Binding Path=String1}></TextBox>
<TextBoxText={Binding Path=String2}></TextBox>
<Button Command={Binding Path=AddCommand}>Add</Button>
<TextBoxText={Binding Path=String3></TextBox>