數據綁定是WPF,Silverlight以及Windows Phone應用開發中最爲常用的開發技術,在基於XAML的Windows Store應用開發中,數據綁定是其開發特性之一,本文將討論Windows 8應用開發數據綁定的使用。
快速理解數據綁定(Data Binding)
對於應用開發人員而言,無論是應用界面還是應用邏輯往往是爲了簡化用戶對於數據層的操作,通過應用控件實現數據同步更新是最直接最簡單的。但是在實際項目開發中,複雜的數據結構以及繁瑣的數據操作使應用控件與數據交互難度增加,對此微軟推出數據綁定實現應用控件直接同步更新數據。簡單理解數據綁定,創建一個對象實例綁定到指定控件,通過DataContext的依賴關係,當對象實例數據改變時,同時自動刷新應用控件數據信息。
數據綁定代碼
數據綁定基本代碼格式:
<TextBox Text="{Binding LastName, Mode=TwoWay}"/>
以上代碼實現綁定數據成員LastName到文本框的Text屬性,其中LastName是數據成員屬性。
實現數據綁定前,首先需要創建綁定數據對象屬性,例如,
- public class Person
- {
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string Email { get; set; }
- }
然後在應用運行時,創建數據成員實例,
- private void LoadAccount()
- {
- this.DataContext = new Person { FirstName = "Kevin", LastName = "Fan", Email = "[email protected]" };
- }
這樣既可實現簡單綁定效果:
數據綁定模式
Windows Store應用支持三種數據綁定模式:
OneTime,一次性綁定,該方式只控件運行時第一次綁定數據,此後,數據源修改控件不在刷新;
OneWay,單向綁定,該方式當數據源更新時,控件同時更新數據,但是當控件數據更新時,數據源不更新;
TwoWay,雙向綁定,該方式當數據源更新時,控件同時更新數據,而當控件數據更新時,數據源同樣更新;
對比以上三種模式,TwoWay綁定較爲常用,而默認情況下,OneWay是默認值。
在上例中,綁定LastName爲TwoWay,雙向模式,即當用戶在控件中修改“姓”,數據源也同時被修改。
數據綁定實時修改 - INotifyPropertyChanged
數據綁定中,另外一個重要的概念是INotifyPropertyChanged接口,該接口用於當數據源與對象屬性綁定時,綁定數據源修改,即通知當前UIElement控件並且更新數據。
例如,在Person.cs中實現INotifyPropertyChanged接口,可以發現該接口僅有一個事件PropertyChanged,使用RaisePropertyChanged實現該事件,
- public class Person : INotifyPropertyChanged
- {
- public string FirstName { get; set; }
- private string _lastname;
- public string LastName
- {
- get { return _lastname; }
- set
- {
- _lastname = value;
- RaisePropertyChanged();
- }
- }
- public string Email { get; set; }
- private void RaisePropertyChanged([CallerMemberName] string caller = "")
- {
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs(caller));
- }
- }
- public event PropertyChangedEventHandler PropertyChanged;
- }
在綁定頁面添加“更新”button, 其代碼:
- private void Button_Click_1(object sender, RoutedEventArgs e)
- {
- person.LastName = "範";
- }
當點擊更新時,Person數據源改變,INotifyPropertyChanged接口通知控件Text="{Binding LastName, Mode=TwoWay}",修改數據內容。
該接口對於實時數據綁定更新非常有用,在後文將經常使用。
Element數據綁定
上文講述是對象實例與數據源的綁定實例。Windows Store應用同時支持控件與控件間屬性綁定,例如,實現CheckBox的IsChecked屬性與Progre***ing的IsActive屬性的綁定,代碼如下:
- <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
- <StackPanel>
- <StackPanel Orientation="Horizontal"
- HorizontalAlignment="Left">
- <TextBlock Text="運行進度:"
- VerticalAlignment="Center"
- Margin="0,0,20,0" />
- <Border BorderThickness="1"
- BorderBrush="#44000000"
- Padding="10">
- <Progre***ing x:Name="Progre***ing1"
- IsActive="{Binding IsChecked, ElementName=chkRun}" />
- </Border>
- </StackPanel>
- <CheckBox Name="chkRun"
- Content="運行?" />
- </StackPanel>
- </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控件
前臺代碼:
- <ComboBox SelectionChanged="cbUserList_SelectionChanged_1" DisplayMemberPath="FullName" />
後臺代碼:
- public sealed partial class MainPage : Page
- {
- public List<Person> Users { get; set; }
- public MainPage()
- {
- this.InitializeComponent();
- LoadUsers();
- }
- /// <summary>
- /// Invoked when this page is about to be displayed in a Frame.
- /// </summary>
- /// <param name="e">Event data that describes how this page was reached. The Parameter
- /// property is typically used to configure the page.</param>
- protected override void OnNavigatedTo(NavigationEventArgs e)
- {
- }
- private void cbUserList_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
- {
- SelectionGrid.DataContext = (e.AddedItems[0] as Person);
- }
- private void LoadUsers()
- {
- Users = new List<Person>();
- Users.Add(new Person { FirstName = "Kevin", LastName = "Fan", Email = "[email protected]" });
- Users.Add(new Person { FirstName = "中國", LastName = "銀光", Email = "[email protected]" });
- Users.Add(new Person { FirstName = "Mike", LastName = "Li", Email = "[email protected]" });
- Users.Add(new Person { FirstName = "Sandy", LastName = "Yang", Email = "[email protected]" });
- cbUserList.ItemsSource = Users;
- }
- }
ListBox控件
前臺代碼:
- <ListBox SelectionChanged="lbUserList_SelectionChanged_1" ItemsSource="{Binding Users}" DisplayMemberPath="FullName" />
後臺代碼:
- public sealed partial class MainPage : Page
- {
- public List<Person> Users { get; set; }
- public MainPage()
- {
- this.InitializeComponent();
- LoadUsers();
- }
- /// <summary>
- /// Invoked when this page is about to be displayed in a Frame.
- /// </summary>
- /// <param name="e">Event data that describes how this page was reached. The Parameter
- /// property is typically used to configure the page.</param>
- protected override void OnNavigatedTo(NavigationEventArgs e)
- {
- }
- private void lbUserList_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
- {
- SelectionGrid.DataContext = (e.AddedItems[0] as Person);
- }
- private void LoadUsers()
- {
- Users = new List<Person>();
- Users.Add(new Person { FirstName = "Kevin", LastName = "Fan", Email = "[email protected]" });
- Users.Add(new Person { FirstName = "中國", LastName = "銀光", Email = "[email protected]" });
- Users.Add(new Person { FirstName = "Mike", LastName = "Li", Email = "[email protected]" });
- Users.Add(new Person { FirstName = "Sandy", LastName = "Yang", Email = "[email protected]" });
- lbUserList.ItemsSource = Users;
- }
- }
本篇介紹Windows store應用開發數據綁定基礎,下篇將介紹更多複雜數據綁定實例。
歡迎留言交流學習,加入QQ羣交流學習:
22308706(一羣) 超級羣500人
37891947(二羣) 超級羣500人
100844510(三羣) 高級羣200人
32679922(四羣) 超級羣500人
23413513(五羣) 高級羣200人
32679955(六羣) 超級羣500人
88585140(八羣) 超級羣500人
128043302(九羣 企業應用開發推薦羣) 高級羣200人
101364438(十羣) 超級羣500人
68435160(十一羣 企業應用開發推薦羣)超級羣500人