Binding是Wpf的核心内容之一
1、下面是Binding基础的一个例子。
XAML:
<Grid> <TextBox x:Name= "myTextBox" Height= "80" HorizontalAlignment= "Left" VerticalAlignment= "Top" Width= "200" /> <Button Height= "23" HorizontalAlignment= "Left" Margin= "38,89,0,0" Name= "button1" VerticalAlignment= "Top" Width= "75" Click= "button1_Click" >Button</Button> </Grid> |
C# Code
public partial class BindingTestxaml : Window { Customer cust; public BindingTestxaml() { InitializeComponent(); BindingTest(); } private void BindingTest() { //准备数据源 cust = new Customer(); // cust.Name = "Tom"; //准备Binding Binding bind = new Binding(); bind.Source = cust; bind.Path = new System.Windows.PropertyPath( "Name" ); //使用Binding连接数据源与Binding目标 BindingOperations.SetBinding(myTextBox, TextBox.TextProperty, bind); } private void button1_Click( object sender, RoutedEventArgs e) { cust.Name += " Tom" ; } } public class Customer:INotifyPropertyChanged { private string name; public string Name { get { return name; } set { this .name = value; //激发事件 if (PropertyChanged != null ) this .PropertyChanged.Invoke( this , new PropertyChangedEventArgs( "Name" )); } } #region INotifyPropertyChanged 成员 public event PropertyChangedEventHandler PropertyChanged; #endregion } |
当然上面的绑定也可以变成一句话的形式:如
//使用Binding连接数据源与Binding目标 BindingOperations.SetBinding(myTextBox, TextBox.TextProperty, new Binding( "Name" ) { Source= cust = new Customer()}); |
2、没有Source的Binding——使用DataContext作为Binding的源,下面是一个简单的例子
先创建一个名为Sutdent的类,它有三个ID,Name,Age三个属性:
public class Student { public string ID{ get ; set ;} public string Name { get ; set ; } public string Age { get ; set ; } } |
然后XAML创建程序UI:
<StackPanel Background= "LightBlue" Margin= "0,118,0,0" HorizontalAlignment= "Right" Width= "201" Height= "122" VerticalAlignment= "Top" > <StackPanel.DataContext> <local:Student ID= "10" Name= "Work Hard Work Smart" Age= "30" /> </StackPanel.DataContext> <TextBox Height= "23" HorizontalAlignment= "Center" Margin= "10" Name= "textBox10" VerticalAlignment= "Top" Text= "{Binding Path=ID}" Width= "164" /> <TextBox Height= "23" HorizontalAlignment= "Center" Margin= "10" Name= "textBox11" VerticalAlignment= "Top" Text= "{Binding Path=Name}" Width= "164" /> <TextBox Height= "23" HorizontalAlignment= "Center" Name= "textBox12" VerticalAlignment= "Top" Text= "{Binding Path=Age}" Width= "164" /> </StackPanel> |
三个TextBox的Text通过Binding获取值,Bindng指定了Path,没有指定Source。
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?