Silverlight XAML TextBlock 中的当前日期
我来自 Flex,在那里你可以在花括号内做任何事情。我试图让 TextBlock
来显示今天的日期和时间,而无需仅用 C# 进行编码。我尝试了以下许多不同的变体,但没有成功。
TextBlock Text="{Source=Date, Path=Now, StringFormat='dd/MM/yyyy'}"
我知道我可能只需设置一个属性 MyDate
并绑定到该属性,但为什么我不能直接绑定到 DateTime.Now
属性?
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 coding it in C#. I have tried many different variations of the following with no luck.
TextBlock Text="{Source=Date, Path=Now, StringFormat='dd/MM/yyyy'}"
I know I could probably just set a property MyDate
and bind to that but why can't I bind directly to the DateTime.Now
property?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Silverlight 中的绑定需要 Source 对象或 Dependency 对象。从该源对象,您可以绑定到属性(因此根据定义,您将绑定到实例成员)或依赖项属性。
由于
DateTime.Now
是一个静态属性,您无法在 Silverlight 中直接绑定到它,因此需要一些代码。下一个最好的事情是使用代码来: -因此我们可以分析我们需要两件事。
为了处理第一个项目,我将创建一个
StaticSurrogate
类,在其中为我们需要访问的静态属性创建实例属性:-现在我们需要一种方法来格式化日期时间。值转换器是完成这项工作的正确工具,它大量借鉴了这个Tim Heuer 博客:-
有了这两个类,我们现在可以在 Xaml 中完成剩下的工作,首先我们需要在资源中使用这些类的实例:-
现在我们可以连接
TextBlock
:-请注意,这种方法具有以下优点:-
StaticSurrogate
类中。Binding in Silverlight requires a Source object or a Dependency object. From that source object you can bind to Properties (hence by definition you are binding to instance members) or Dependency Properties.
Since
DateTime.Now
is a static property you cannot bind to it in Silverlight directly, hence some code is needed. The next best thing is to use code to:-Hence we can analyse that we need two things.
To handle the first item I would create a
StaticSurrogate
class, where I would create instance properties for the static properties that we need access to:-Now we need a way to format a Date time. A value converter is the right tool for this job, borrowing heavily from this Tim Heuer Blog :-
With these two classes in place we can now do the rest in Xaml, first we need instances of these classes in our resources:-
Now we can wire up the
TextBlock
:-Note that this approach has the following advantages:-
StaticSurrogate
class.即使您可以在 Silverlight 的 XAML 中声明 DateTime.Now (因为您可以在 WPF 中 - http://soumya.wordpress.com/2010/02/12/wpf-simplified-part-11-xaml-tricks/),您遇到的问题是您的时间不会更新。如果您使用每秒更新的本地计时器,您可以确保您的时间也会更新。
在 xaml ala: 中声明此实例,
并使用绑定来确保始终反映您的时间。
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.
Declare an instance of this in xaml ala:
and use the binding to ensure that your time is always reflected.