使用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应用商店中找到Timer
。也许这是另一种方法吗?
答案 0 :(得分:2)
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实例