前台代码:
<Window x:Class="WpfApplication1.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">
<Grid>
<TextBox Height="23" Margin="10,10,9,0" Name="textBox1" VerticalAlignment="Top" />
<TextBox Height="23" Margin="10,41,9,0" Name="textBox2" VerticalAlignment="Top" />
<Slider Height="21" Margin="10,73,9,0" Name="slider1" VerticalAlignment="Top" Maximum="100" />
<Button Content="Button" Height="40" HorizontalAlignment="Left" Margin="176,164,0,0" Name="button1" VerticalAlignment="Top" Width="156" Click="button1_Click" />
</Grid>
</Window>
后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Test test = new Test();
public MainWindow()
{
InitializeComponent();
Binding binding = new Binding();
binding.Source = test;
binding.Path = new PropertyPath("Id");
this.textBox1.SetBinding(TextBox.TextProperty, binding);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
test.Id += 10;
}
}
public class Test : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged; // 这个接口仅包含一个事件而已
private int id;
public int Id
{
get { return id; }
set
{
id = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Id")); // 通知Binding是“Id”这个属性的值改变了
}
}
}
private int age;
public int Age
{
get { return age; }
set { age = value; } // Age的值改变时不进行通知
}
}
}
代码功能:
该代码实现test 对象的Id属性与textBox1的text属性绑定;