XMAL代码
<StackPanel Margin="5" Background="LightBlue">
<TextBox Margin="5" Height="50" x:Name="txtone"/>
<Button Margin="5" Height="40" Content="累计" Click="btn_Click"/>
</StackPanel>
User类
//继承通知事件这个接口
class User:INotifyPropertyChanged
{
//声明一个属性改变事件
public event PropertyChangedEventHandler PropertyChanged;
private double chengji;
public double ChengJi
{
get { return chengji; }
set
{
chengji = value;
if (PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("ChengJi"));
}
}
}
}
CS代码
public partial class MainWindow : Window
{
User u = new User();
public MainWindow()
{
InitializeComponent();
//----------------------------------写法1-------------------------------------------
//Binding binding = new Binding();
//数据源是User类
//binding.Source = u;
//路径是Chengji这个属性
//binding.Path=new PropertyPath("ChengJi");
//进行绑定,第一个参数是绑定的目标,就是你要往哪绑定,第二个参数三你要往目标的哪个属性上绑,第三个参数就就是说你要与哪个实例关联
//BindingOperations.SetBinding(this.txtone, TextBox.TextProperty, binding);
//----------------------------------写法2-------------------------------------------
this.txtone.SetBinding(TextBox.TextProperty, new Binding("ChengJi") { Source = u });
}
private void btn_Click(object sender, RoutedEventArgs e)
{
u.ChengJi += 1;
}
}