数据绑定的基础

先用一个最简单的例子来演示数据绑定。

新建一个项目TestData来测试,拖拽两个控件到屏幕上:TextBox和Slider。

给Slider的Name设置为slider1,然后我们给两个控件之间添加数据绑定,使得TextBox始终显示滑动条内的进度值。

然后给Text属性添加数据绑定,并且指定对象为slider1,完整代码如下:

  1. <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">  
  2.        <TextBox HorizontalAlignment="Center" Margin="0,-100,0,0" TextWrapping="Wrap"   
  3.                 Text="{Binding Value, Mode=TwoWay, ElementName=slider1}" VerticalAlignment="Center"/>  
  4.        <Slider x:Name="slider1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Height="30"/>  
  5.   
  6.    </Grid>  

运行的结果就是1.拖动滑块时文本框的数值也随之改变2.文本框内容改变时滚动条也会跟着改变,这就是TwoWay:


那么怎么自己去写数据绑定呢?

新建一个Person类来试验一下。

[csharp] view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace TestData  
  8. {  
  9.     class Person  
  10.     {  
  11.         public string Name  
  12.         {  
  13.             get;  
  14.             set;  
  15.         }  
  16.   
  17.         public int Age  
  18.         {  
  19.             get;  
  20.             set;  
  21.         }  
  22.     }  
  23. }  

然后在主页面拖拽一个TextBox和两个按钮,一个按钮用来读出Person的值,一个是用来修改Person的值:


先给TextBox命名为text1以便后面使用。

双击读取的按钮,跳转到了后台的c#文件。

在类中声明一个Person对象:        Person myPerson = new Person();

然后在OnNavigatedTo方法中判断,如果是NavigationMode.New则设置text1的DataContent为前面声明的myPerson。

这里可以把DataContent理解为数据源。

然后点击按钮的监听方法里,将读取到的Person内容显示出来,在点击第二个按钮的时候将Person的name显示为当前的毫秒数值。

完整的代码如下:

[csharp] view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using Windows.Foundation;  
  6. using Windows.Foundation.Collections;  
  7. using Windows.UI.Popups;  
  8. using Windows.UI.Xaml;  
  9. using Windows.UI.Xaml.Controls;  
  10. using Windows.UI.Xaml.Controls.Primitives;  
  11. using Windows.UI.Xaml.Data;  
  12. using Windows.UI.Xaml.Input;  
  13. using Windows.UI.Xaml.Media;  
  14. using Windows.UI.Xaml.Navigation;  
  15.   
  16. // “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍  
  17.   
  18. namespace TestData  
  19. {  
  20.     /// <summary>  
  21.     /// 可用于自身或导航至 Frame 内部的空白页。  
  22.     /// </summary>  
  23.     public sealed partial class MainPage : Page  
  24.     {  
  25.   
  26.         Person myPerson = new Person(){ Name = "why" , Age = 20 };  
  27.         public MainPage()  
  28.         {  
  29.             this.InitializeComponent();  
  30.         }  
  31.   
  32.         /// <summary>  
  33.         /// 在此页将要在 Frame 中显示时进行调用。  
  34.         /// </summary>  
  35.         /// <param name="e">描述如何访问此页的事件数据。Parameter  
  36.         /// 属性通常用于配置页。</param>  
  37.         protected override void OnNavigatedTo(NavigationEventArgs e)  
  38.         {  
  39.             if (e.NavigationMode == NavigationMode.New)  
  40.             {  
  41.                 text1.DataContext = myPerson;  
  42.             }  
  43.         }  
  44.   
  45.         private void Button_Click_1(object sender, RoutedEventArgs e)  
  46.         {  
  47.             MessageDialog myDialog = new MessageDialog(myPerson.Name);  
  48.             myDialog.ShowAsync();  
  49.         }  
  50.   
  51.         private void Button_Click_2(object sender, RoutedEventArgs e)  
  52.         {  
  53.             myPerson.Name = DateTime.Now.Millisecond.ToString();  
  54.         }  
  55.     }  
  56. }  

然后在xaml页面设置textbox的数据绑定,将其绑定到数据源的Name属性上(前面设置的数据源):

完整的xaml代码如下:

  1. <Page  
  2.     x:Class="TestData.MainPage"  
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  5.     xmlns:local="using:TestData"  
  6.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  7.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  8.     mc:Ignorable="d">  
  9.   
  10.     <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">  
  11.         <TextBox x:Name="text1" HorizontalAlignment="Center" Margin="0,0,0,0" TextWrapping="Wrap"   
  12.                  Text="{Binding Name}" VerticalAlignment="Center"/>  
  13.         <Button Content="读取" HorizontalAlignment="Center" Margin="0,-100,0,0" VerticalAlignment="Center" Click="Button_Click_1"/>  
  14.         <Button Content="改变" HorizontalAlignment="Center" Margin="0,100,0,0" VerticalAlignment="Center" Click="Button_Click_2"/>  
  15.     </Grid>  
  16. </Page>  


运行项目,发现显示的是why,但是点击修改之后textbox中的值并没有改变,因为text不知道其中发生了变化。

那么如何在Name发生变化的时候立即得知?

我们需要修改Person这个类。

在数据绑定中,建议大家实现一个INotifyPropertyChanged接口。

它只有一个成员,就是PropertyChanged事件。

将set稍作修改即可。完整的Person.cs文件如下:

[csharp] view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace TestData  
  9. {  
  10.     class Person : INotifyPropertyChanged  
  11.     {  
  12.         private string _name;  
  13.         public string Name  
  14.         {  
  15.             get  
  16.             {  
  17.                 return _name;  
  18.             }  
  19.             set  
  20.             {  
  21.                 _name = value;  
  22.                 if (PropertyChanged != null)  
  23.                 {  
  24.                     PropertyChanged(thisnew PropertyChangedEventArgs("Name"));  
  25.                 }  
  26.             }  
  27.         }  
  28.   
  29.         private int _age;  
  30.         public int Age  
  31.         {  
  32.             get  
  33.             {  
  34.                 return _age;  
  35.             }  
  36.             set  
  37.             {  
  38.                 _age = value;  
  39.                 if (PropertyChanged != null)  
  40.                 {  
  41.                     PropertyChanged(thisnew PropertyChangedEventArgs("Age"));  
  42.                 }  
  43.             }  
  44.         }  
  45.   
  46.         public event PropertyChangedEventHandler PropertyChanged;  
  47.     }  
  48. }  


此时再运行,点击修改的时候TextBox里面就会跟着变化了。



顺便说一下,绑定模式一共分三种,

  • OneTime:一次绑定
  • OneWay:单向绑定
  • TwoWay:双向绑定
子控件会默认继承父控件的绑定数据,这就是数据上下文的概念。
比如上面说到的绑定数据源,也可以写成:this.DataContext = myPerson;
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值