如果我们需要将方法的返回值Binding一下,那就可以使用ObjectDataProvider作为Binding的源
XAML代码
<Window x:Class="使用ObjectDataProvider作为Binding的源.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel Background="LightBlue">
<TextBox x:Name="txt1" Margin="5"/>
<TextBox x:Name="txt2" Margin="5"/>
<TextBox x:Name="txtresult" Margin="5"/>
</StackPanel>
</Window>
CS代码
namespace 使用ObjectDataProvider作为Binding的源
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ObjectDataProvider odp = new ObjectDataProvider();
//把一个Add对象赋值给ObjectInstantce这个属性
odp.ObjectInstance = new Add();
//将使用的方法名字赋值给MethodName属性
odp.MethodName = "Jia";
//两个参数,要是重载的化,就根据这快给不用的参数就行
odp.MethodParameters.Add("0");
odp.MethodParameters.Add("0");
Binding bind1 = new Binding("MethodParameters[0]")
{
Source=odp,
BindsDirectlyToSource=true,
UpdateSourceTrigger=UpdateSourceTrigger.PropertyChanged
};
Binding bind2 = new Binding("MethodParameters[1]")
{
Source = odp,
BindsDirectlyToSource = true,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
Binding result = new Binding(".") { Source=odp};
this.txt1.SetBinding(TextBox.TextProperty, bind1);
this.txt2.SetBinding(TextBox.TextProperty, bind2);
this.txtresult.SetBinding(TextBox.TextProperty, result);
}
}
}
Add类(添加的方法)
namespace 使用ObjectDataProvider作为Binding的源
{
class Add
{
public string Jia(string str1,string str2)
{
double x = 0;
double y = 0;
double z = 0;
if(double.TryParse(str1,out x) && double.TryParse(str2,out y)){
z = x + y;
return z.ToString();
}
return "异常了";
}
}
}