WPF之Binding基础一 UI Binding Source

来源:互联网 发布:windows关机指令 编辑:程序博客网 时间:2024/06/05 01:51

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;
}
}


<script type="text/javascript"><!--google_ad_client = "ca-pub-1944176156128447";/* cnblogs 首页横幅 */google_ad_slot = "5419468456";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>