代码之家  ›  专栏  ›  技术社区  ›  Tony Smith

Silverlight XAML文本块中的当前日期

  •  8
  • Tony Smith  · 技术社区  · 15 年前

    我来自flex,在那里你可以在花括号内做任何事情。我想得到一个 TextBlock 显示今天的日期和时间,而不只是用c编码。我试过很多不同的变体,但都不走运。

    TextBlock Text="{Source=Date, Path=Now, StringFormat='dd/MM/yyyy'}"
    

    我知道我也许可以设置一个属性 MyDate 但为什么我不能直接绑定到 DateTime.Now 财产?

    3 回复  |  直到 13 年前
        1
  •  14
  •   AnthonyWJones    15 年前

    Silverlight中的绑定需要源对象或依赖对象。从该源对象可以绑定到属性(因此根据定义,您绑定到实例成员)或依赖项属性。

    自从 DateTime.Now 是一个静态属性,不能在Silverlight中直接绑定到它,因此需要一些代码。接下来最好的方法是使用代码来:

    • 确保尽可能多的所需内容可以用xaml表示
    • 以尽可能分离的方式这样做。

    因此我们可以分析我们需要两件事。

    1. 将datetime的静态成员公开为某个对象的实例属性
    2. 有一些方法可以将日期时间格式化为所需的输出。

    为了处理第一个项目,我将创建 StaticSurrogate 类,在该类中,我将为需要访问的静态属性创建实例属性:

    public class StaticSurrogate
    {
        public DateTime Today { get { return DateTime.Today; } }
        public DateTime Now { get { return DateTime.Now; } }
    }
    

    现在我们需要一种格式化日期时间的方法。一个值转换器是这个工作的正确工具,从中得到了很大的帮助 Tim Heuer Blog -

    public class FormatConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (parameter != null)
            {
                string formatterString = parameter.ToString();
    
                if (!String.IsNullOrEmpty(formatterString))
                {
                    return String.Format(culture, String.Format("{{0:{0}}}", formatterString), value);
                }
            }
    
            return (value ?? "").ToString();
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    有了这两个类,我们现在可以在xaml中完成剩下的工作,首先我们需要在我们的资源中使用这些类的实例:

    <UserControl.Resources>
        <local:StaticSurrogate x:Key="Static" />
        <local:FormatConverter x:Key="Formatter" />     
    </UserControl.Resources>
    

    现在我们可以把 TextBlock -

    <TextBlock Text="{Binding Today, Source={StaticResource Static},
        Converter={StaticResource Formatter}, ConverterParameter='dd MMM yyy'}" />
    

    注意,这种方法有以下优点:

    • 我们不需要向放置textblock的usercontrol添加代码,也不需要处理任何数据上下文。
    • 静态资源可以放在app.resources中,这将使文本块的创建完全独立于向usercontrol添加任何其他内容。
    • 用于显示日期的格式可以单独修改。
    • 可以很容易地将对其他静态属性的访问添加到 静态代理 班级。
        2
  •  7
  •   nyxtom    15 年前

    即使您可以声明datetime,现在在silverlight的xaml中(因为您可以在wpf中- http://soumya.wordpress.com/2010/02/12/wpf-simplified-part-11-xaml-tricks/ ),您的时间无法更新。如果您使用的本地计时器在秒时更新,则可以确保您的时间也会更新。

    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 = "dddd, 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
    }
    

    在xaml ala中声明此实例:

    <local:LocalTimer x:Key="theTime" Enabled="True" />
    

    并使用绑定来确保您的时间始终得到反映。

    <TextBlock Text="{Binding Source={StaticResource theTime}, Path=FormattedDate, Mode=OneWay}" x:Name="TodaysDate" />
    <TextBlock Text="{Binding Source={StaticResource theTime}, Path=FormattedTime, Mode=OneWay}" x:Name="CurrentTime" />
    
        3
  •  1
  •   knockando    14 年前
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    
    Text="{Binding Source={x:Static sys:DateTime.Today}, StringFormat='Today is {0:dddd, MMMM dd}'}"