Current Date in Silverlight XAML TextBlock

后端 未结 3 1491
闹比i
闹比i 2021-02-09 01:59

I am coming from Flex where you can do just about anything inside of curly braces. I am trying to get a TextBlock to display today\'s Date and Time without just cod

3条回答
  •  再見小時候
    2021-02-09 02:30

    Even if you could declare DateTime.Now in Silverlight's XAML (since you can in WPF - http://soumya.wordpress.com/2010/02/12/wpf-simplified-part-11-xaml-tricks/), you have the issue that your time won't update. If you use a local timer that updates on the second you can ensure that your time will update as well.

    public class LocalTimer : INotifyPropertyChanged
    {
        private DispatcherTimer timer;
    
        public LocalTimer()
        {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1.0);
            timer.Tick += new EventHandler(TimerCallback);
            this.TimeFormat = "hh:mm:ss";
            this.DateFormat = "ffffdd, MMMM dd";
        }
    
        private void TimerCallback(object sender, EventArgs e)
        {
            PropertyChanged(this, new PropertyChangedEventArgs("FormattedDate"));
            PropertyChanged(this, new PropertyChangedEventArgs("FormattedTime"));
        }
    
        public bool Enabled
        {
            get { return this.timer.IsEnabled; }
            set { if (value) this.timer.Start(); else this.timer.Stop(); }
        }
    
        public string FormattedDate { get { return DateTime.Now.ToString(this.DateFormat); } set {} }
        public string FormattedTime { get { return DateTime.Now.ToString(this.TimeFormat); } set{} }
    
        public string TimeFormat { get; set; }
        public string DateFormat { get; set; }
    
        #region INotifyPropertyChanged Members
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        #endregion
    }
    

    Declare an instance of this in xaml ala:

    
    

    and use the binding to ensure that your time is always reflected.

    
    
    

提交回复
热议问题