[英]How to create Binding in Windows Store App
使用Visual Studio 2013,C#
嘗試在首頁上創建與當前時間綁定的內容-以便每秒鍾更改一次頁面。 (只是嘗試更好地了解綁定)
做了什么:
通過實現INotifyPropertyChanged
創建特殊類
using System.ComponentModel; //this class must be used for binding changed time on main page namespace Memo { //Implement INotifiyPropertyChanged //interface to subscribe for property change notifications class DateTimeNow : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string _currentDateTimeNow; //simple prop public string CurrentDateTimeNow { get { return _currentDateTimeNow; } set { if (_currentDateTimeNow != value) { _currentDateTimeNow = value; RaisePropertyChanged("CurrentDateTimeNow"); } } } //event private void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
在XAML中添加反映代碼(mainPage.xaml)
TextBlock x:Name="currentTime" FontSize="25" Style="{StaticResource SubheaderTextBlockStyle}" Margin="20,10,0,0" Text="{Binding Path=CurrentDateTimeNow}"
添加一些代碼后(mainPage.xaml.cs)
public MainPage() { this.InitializeComponent(); this.navigationHelper = new NavigationHelper(this); this.navigationHelper.LoadState += navigationHelper_LoadState; this.navigationHelper.SaveState += navigationHelper_SaveState; //add binding to main page //currentTime.DataContext = DateTime.Now; //initialize instances _dateTimeNow = new DateTimeNow(); //get current time _dateTimeNow.CurrentDateTimeNow = DateTime.Now.ToString(); //register event _dateTimeNow.PropertyChanged += _dateTimeNow_PropertyChanged; //move data to text block ShowCurrentTime(currentTime); } //move information from prop to the text block private void ShowCurrentTime(TextBlock textBlock) { textBlock.Text = _dateTimeNow.CurrentDateTimeNow; } //do on changes time void _dateTimeNow_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { ShowCurrentTime(currentTime); }
結果是時間僅反映當前時間-啟動程序的時間:
但是每一秒都什么都沒發生-時間沒有更新。 猜猜是因為我沒有每秒添加一些代碼來更新屬性-如果屬性更改了-我的textBox信息將被更新。
問題-我該如何編碼,該屬性可以根據時間變化每秒更改一次? 那么,為什么我要問-在Windows Store應用中找不到Timer
。 也許這是另一種方法嗎?
使用DispatcherTimer :
public MainPage()
{
this.InitializeComponent();
...
var dateTimeNow = new DateTimeNow();
DataContext = dateTimeNow;
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
timer.Tick += (o, e) => dateTimeNow.CurrentDateTimeNow = DateTime.Now.ToString();
timer.Start();
}
還要注意,您_dateTimeNow_PropertyChanged
處理程序,因為TextBlock已經由CurrentDateTimeNow
綁定更新,只要您已將MainPage的DataContext
設置為DateTimeNow實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.