Binding to DateTime.Now. Update the value

前端 未结 4 1705
星月不相逢
星月不相逢 2020-12-11 01:47

Well, I needed to bind DateTime.Now to a TextBlock, I used that:

 Text=\"{Binding Source={x:Static System:DateTime.Now},StringFormat=\'HH:mm:ss tt\'}\"
         


        
4条回答
  •  囚心锁ツ
    2020-12-11 02:36

    Edited (I didn't account for him wanting to auto-update):

    Here's a link of a 'Ticker' class that uses INotifyPropertyChanged so it'll auto-update. Here's the code from the site:

    namespace TheJoyOfCode.WpfExample
    {
        public class Ticker : INotifyPropertyChanged
        {
            public Ticker()
            {
                Timer timer = new Timer();
                timer.Interval = 1000; // 1 second updates
                timer.Elapsed += timer_Elapsed;
                timer.Start();
            }
    
            public DateTime Now
            {
                get { return DateTime.Now; }
            }
    
            void timer_Elapsed(object sender, ElapsedEventArgs e)
            {
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Now"));
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
        }
    }
    
    
    
       
    
    
    
    

    Declare:

    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    

    Now this will work:

    
    

提交回复
热议问题