簡體   English   中英

如何僅在XAML中更新DateTime.Now綁定?

[英]How to update DateTime.Now binding purely within XAML?

假設我有一個StatusBarItem在我的StatusBar ,其唯一目的是顯示當前DateTime信息。 我知道如何從代碼隱藏中完成此工作; 但是,我正在嘗試找出一種僅從XAML執行此操作的方法。

這是我使用的XAML代碼:

<StatusBarItem Content="{Binding Source={x:Static sys:DateTime.Now}, StringFormat='dd/MM/yyyy hh:mm tt'}"/>

它顯示了我運行程序時的DateTime信息,但是即使有可能,我也無法找到一種純粹通過XAML更新它的方法。

您不能僅將其嵌入XAML中,而是要做類似的事情,

映射MSDN時資源中不支持DateTime。可以通過實現INotifyPropertyChanged來使用計時器,

    namespace Sample.WpfExample
    {
    public class TickerC : INotifyPropertyChanged
    {
        public TickerC()
        {
            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;
    }

在XAML中

   <Window.Resources>
   <src:TickerC x:Key="ticker" />
   </Window.Resources>

<StatusBarItem Content="{Binding Source={StaticResource ticker}, Path=Now, Mode=OneWay}"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM