下面实例展示了WPF内嵌代码和后台代码混合使用,一个简单基础的实例:
xaml文件:
<Window x:Class="WPF内嵌代码和后台代码混合使用.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="" Width="">
<Grid Background="BlanchedAlmond">
<Canvas Height="" HorizontalAlignment="Left" Margin="12,12,0,0" Name="canvas1" VerticalAlignment="Top" Width="">
<TextBox Canvas.Left="" Canvas.Top="" Height="" Name="textBox1" Width="" />
<TextBox Canvas.Left="" Canvas.Top="" Height="" Name="textBox2" Width="" />
<TextBox Canvas.Left="" Canvas.Top="" Height="" Name="textBox3" Width="" />
<Label Canvas.Left="" Canvas.Top="" Content="OUT:" Height="" Name="label1" />
<Label Canvas.Left="" Canvas.Top="" Content="X:" Height="" Name="label2" />
<Label Canvas.Left="" Canvas.Top="" Content="Y:" Height="" Name="label3" />
<Button Content="+" Height="" Name="button1" Width="" Click="button1_Click" Canvas.Left="" Canvas.Top="" />
<Button Content="-" Height="" Name="button2" Width="" Canvas.Left="" Canvas.Top="" Click="button2_Click" />
<Button Content="*" Height="" Name="button3" Width="" Canvas.Left="" Canvas.Top="" Click="button3_Click" />
<Button Content="/" Height="" Name="button4" Width="" Canvas.Left="" Canvas.Top="" Click="button4_Click" />
<x:Code>
<![CDATA[
void button1_Click(object sender, RoutedEventArgs e) {
this.GetValue();
} int Plus(int x ,int y){
return x +y;
}
void button2_Click(object sender, RoutedEventArgs e) {
this.GetValue1();
} int Minus(int x ,int y){
return x -y;
}
void button3_Click(object sender, RoutedEventArgs e) {
this.GetValue2();
} int Multiply(int x ,int y){
return x *y;
}
void button4_Click(object sender, RoutedEventArgs e) {
this.GetValue3();
} int Divide(int x ,int y){
return x /y;
}
]]> </x:Code>
</Canvas>
</Grid>
</Window>
后台简单代码:
public void GetValue() {
this.textBox3.Text = this.Plus(int.Parse(this.textBox1.Text), int.Parse(this.textBox2.Text)).ToString();
}
public void GetValue1()
{
this.textBox3.Text = this.Minus(int.Parse(this.textBox1.Text), int.Parse(this.textBox2.Text)).ToString();
}
public void GetValue2()
{
this.textBox3.Text = this.Multiply(int.Parse(this.textBox1.Text), int.Parse(this.textBox2.Text)).ToString();
}
public void GetValue3()
{
this.textBox3.Text = this.Divide(int.Parse(this.textBox1.Text), int.Parse(this.textBox2.Text)).ToString();
}
效果展示: