Windows 8實例教程系列 - 數據綁定基礎實例

 

數據綁定是WPF,Silverlight以及Windows Phone應用開發中最爲常用的開發技術,在基於XAML的Windows Store應用開發中,數據綁定是其開發特性之一,本文將討論Windows 8應用開發數據綁定的使用。

快速理解數據綁定(Data Binding)

對於應用開發人員而言,無論是應用界面還是應用邏輯往往是爲了簡化用戶對於數據層的操作,通過應用控件實現數據同步更新是最直接最簡單的。但是在實際項目開發中,複雜的數據結構以及繁瑣的數據操作使應用控件與數據交互難度增加,對此微軟推出數據綁定實現應用控件直接同步更新數據。簡單理解數據綁定,創建一個對象實例綁定到指定控件,通過DataContext的依賴關係,當對象實例數據改變時,同時自動刷新應用控件數據信息。

 

 

數據綁定代碼

數據綁定基本代碼格式:

<TextBox Text="{Binding LastName, Mode=TwoWay}"/>

以上代碼實現綁定數據成員LastName到文本框的Text屬性,其中LastName是數據成員屬性。

實現數據綁定前,首先需要創建綁定數據對象屬性,例如,

  1. public class Person 
  2.    { 
  3.        public string FirstName { getset; } 
  4.        public string LastName { getset; } 
  5.        public string Email { getset; } 
  6.    } 

然後在應用運行時,創建數據成員實例,

  1. private void LoadAccount() 
  2.         { 
  3.             this.DataContext = new Person { FirstName = "Kevin", LastName = "Fan", Email = "[email protected]" }; 
  4.         }   

這樣既可實現簡單綁定效果:

數據綁定模式

Windows Store應用支持三種數據綁定模式:

OneTime,一次性綁定,該方式只控件運行時第一次綁定數據,此後,數據源修改控件不在刷新;

OneWay,單向綁定,該方式當數據源更新時,控件同時更新數據,但是當控件數據更新時,數據源不更新;

TwoWay,雙向綁定,該方式當數據源更新時,控件同時更新數據,而當控件數據更新時,數據源同樣更新;

對比以上三種模式,TwoWay綁定較爲常用,而默認情況下,OneWay是默認值。

在上例中,綁定LastName爲TwoWay,雙向模式,即當用戶在控件中修改“姓”,數據源也同時被修改。

數據綁定實時修改 - INotifyPropertyChanged

數據綁定中,另外一個重要的概念是INotifyPropertyChanged接口,該接口用於當數據源與對象屬性綁定時,綁定數據源修改,即通知當前UIElement控件並且更新數據。

例如,在Person.cs中實現INotifyPropertyChanged接口,可以發現該接口僅有一個事件PropertyChanged,使用RaisePropertyChanged實現該事件,

 

  1. public class Person : INotifyPropertyChanged 
  2.    { 
  3.        public string FirstName { getset; } 
  4.  
  5.        private string _lastname; 
  6.        public string LastName  
  7.        { 
  8.            get { return _lastname; } 
  9.            set 
  10.            { 
  11.                _lastname = value; 
  12.                RaisePropertyChanged(); 
  13.            } 
  14.        } 
  15.  
  16.        public string Email { getset; } 
  17.  
  18.        private void RaisePropertyChanged([CallerMemberName] string caller = ""
  19.        { 
  20.            if (PropertyChanged != null
  21.            { 
  22.                PropertyChanged(thisnew PropertyChangedEventArgs(caller)); 
  23.            } 
  24.        } 
  25.  
  26.        public event PropertyChangedEventHandler PropertyChanged; 
  27.    } 

在綁定頁面添加“更新”button, 其代碼:

 

  1. private void Button_Click_1(object sender, RoutedEventArgs e) 
  2.        { 
  3.            person.LastName = "範"
  4.        }    

當點擊更新時,Person數據源改變,INotifyPropertyChanged接口通知控件Text="{Binding LastName, Mode=TwoWay}",修改數據內容。

該接口對於實時數據綁定更新非常有用,在後文將經常使用。

Element數據綁定

上文講述是對象實例與數據源的綁定實例。Windows Store應用同時支持控件與控件間屬性綁定,例如,實現CheckBox的IsChecked屬性與Progre***ing的IsActive屬性的綁定,代碼如下:

  1. <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> 
  2.        <StackPanel> 
  3.            <StackPanel Orientation="Horizontal" 
  4.                        HorizontalAlignment="Left"> 
  5.                <TextBlock Text="運行進度:" 
  6.                           VerticalAlignment="Center" 
  7.                           Margin="0,0,20,0" /> 
  8.                <Border BorderThickness="1" 
  9.                        BorderBrush="#44000000" 
  10.                        Padding="10"> 
  11.                    <Progre***ing x:Name="Progre***ing1" 
  12.                                  IsActive="{Binding IsChecked, ElementName=chkRun}" /> 
  13.                </Border> 
  14.            </StackPanel> 
  15.            <CheckBox Name="chkRun" 
  16.                      Content="運行?" /> 
  17.        </StackPanel> 
  18.    </Grid> 

其中綁定代碼中的綁定成員使用Element對象屬性名,並且附加ElementName。

<Progre***ing x:Name="Progre***ing1" IsActive="{Binding IsChecked, ElementName=chkRun}" />

運行效果如下,選中運行CheckBox,運行進度開始:

 

數據綁定與數據轉換(Data Converter)

在Windows 8 XAML實例教程中曾講述過數據轉換器的創建和使用,XAML實例教程系列 - 類型轉換器(Type Converter)

當時代碼是使用VS2012 RC和Windows 8 RP版本創建,所以,本篇代碼進行轉換到VS2012和Windows 8正式版。

 

Windows 8數據綁定控件

爲了方便應用開發,微軟爲開發人員提供了許多數據綁定控件,通過以上綁定方式設置,可以快速的將數據成員集合綁定到對應控件。

ComboBox控件

前臺代碼:

  1. <ComboBox SelectionChanged="cbUserList_SelectionChanged_1" DisplayMemberPath="FullName" /> 

後臺代碼:

 

  1. public sealed partial class MainPage : Page 
  2.     { 
  3.         public List<Person> Users { getset; } 
  4.  
  5.         public MainPage() 
  6.         { 
  7.             this.InitializeComponent(); 
  8.             LoadUsers(); 
  9.         } 
  10.  
  11.         /// <summary> 
  12.         /// Invoked when this page is about to be displayed in a Frame. 
  13.         /// </summary> 
  14.         /// <param name="e">Event data that describes how this page was reached.  The Parameter 
  15.         /// property is typically used to configure the page.</param> 
  16.         protected override void OnNavigatedTo(NavigationEventArgs e) 
  17.         { 
  18.         } 
  19.  
  20.         private void cbUserList_SelectionChanged_1(object sender, SelectionChangedEventArgs e) 
  21.         { 
  22.             SelectionGrid.DataContext = (e.AddedItems[0] as Person); 
  23.         } 
  24.  
  25.         private void LoadUsers() 
  26.         { 
  27.             Users = new List<Person>(); 
  28.  
  29.             Users.Add(new Person { FirstName = "Kevin", LastName = "Fan", Email = "[email protected]" }); 
  30.             Users.Add(new Person { FirstName = "中國", LastName = "銀光", Email = "[email protected]" }); 
  31.             Users.Add(new Person { FirstName = "Mike", LastName = "Li", Email = "[email protected]" }); 
  32.             Users.Add(new Person { FirstName = "Sandy", LastName = "Yang", Email = "[email protected]" }); 
  33.  
  34.             cbUserList.ItemsSource = Users; 
  35.         } 
  36.     } 

 

ListBox控件

 

前臺代碼:

 

  1. <ListBox SelectionChanged="lbUserList_SelectionChanged_1" ItemsSource="{Binding Users}" DisplayMemberPath="FullName" /> 

後臺代碼:

  1. public sealed partial class MainPage : Page 
  2.     { 
  3.         public List<Person> Users { getset; } 
  4.  
  5.         public MainPage() 
  6.         { 
  7.             this.InitializeComponent(); 
  8.             LoadUsers(); 
  9.         } 
  10.  
  11.         /// <summary> 
  12.         /// Invoked when this page is about to be displayed in a Frame. 
  13.         /// </summary> 
  14.         /// <param name="e">Event data that describes how this page was reached.  The Parameter 
  15.         /// property is typically used to configure the page.</param> 
  16.         protected override void OnNavigatedTo(NavigationEventArgs e) 
  17.         { 
  18.         } 
  19.  
  20.         private void lbUserList_SelectionChanged_1(object sender, SelectionChangedEventArgs e) 
  21.         { 
  22.             SelectionGrid.DataContext = (e.AddedItems[0] as Person); 
  23.         } 
  24.  
  25.         private void LoadUsers() 
  26.         { 
  27.             Users = new List<Person>(); 
  28.  
  29.             Users.Add(new Person { FirstName = "Kevin", LastName = "Fan", Email = "[email protected]" }); 
  30.             Users.Add(new Person { FirstName = "中國", LastName = "銀光", Email = "[email protected]" }); 
  31.             Users.Add(new Person { FirstName = "Mike", LastName = "Li", Email = "[email protected]" }); 
  32.             Users.Add(new Person { FirstName = "Sandy", LastName = "Yang", Email = "[email protected]" }); 
  33.  
  34.             lbUserList.ItemsSource = Users; 
  35.         } 
  36.     } 

本篇介紹Windows store應用開發數據綁定基礎,下篇將介紹更多複雜數據綁定實例。

 

 

本篇源代碼

 

歡迎留言交流學習,加入QQ羣交流學習:

22308706(一羣) 超級羣500人 
37891947(二羣) 超級羣500人 
100844510(三羣) 高級羣200人 
32679922(四羣) 超級羣500人 
23413513(五羣) 高級羣200人 
32679955(六羣) 超級羣500人 
88585140(八羣) 超級羣500人 
128043302(九羣 企業應用開發推薦羣) 高級羣200人 
101364438(十羣) 超級羣500人 

68435160(十一羣 企業應用開發推薦羣)超級羣500人

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章