wpf,如何绑定当前日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4383537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
wpf,How to bind Current Date?
提问by doull
I have a TextBlock control to which I would like to bind current System Date , how can I do that by Code Behind ?
我有一个 TextBlock 控件,我想将当前的 System Date 绑定到该控件,我如何通过代码隐藏来做到这一点?
The goal is to display in this TecBlock the current System Date and Time and I do not need the control refresh all the time ,only once.
目标是在此 TecBlock 中显示当前系统日期和时间,并且我不需要一直刷新控件,只需要刷新一次。
I hope that is most simple Code.I don't want to Create dateTime Property. follow is my code:it is Wrong that it can't find BindSource
我希望这是最简单的代码。我不想创建 dateTime 属性。以下是我的代码:它找不到 BindSource 是错误的
Binding bd = new Binding("System.DateTime.Now");
bd.Source = this;
textBox.SetBinding(TextBox.TextProperty, bd);
Thanks for help
感谢帮助
回答by Kishore Kumar
This will show the Current date only once .
这将只显示当前日期一次。
create a namespace alias:
创建命名空间别名:
xmlns:sys="clr-namespace:System;assembly=mscorlib"
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Today},
StringFormat='{}{0:dddd, MMMM dd, yyyy}'}"/>
回答by BrokenGlass
Well technically speaking you could bind the current time as in the sample below, but without a proper binding as SLaks mentioned you won't be able to refresh it at all.
从技术上讲,您可以像下面的示例一样绑定当前时间,但是如果没有正确的绑定,正如 SLaks 提到的那样,您将根本无法刷新它。
<Window x:Class="testWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ObjectDataProvider x:Key="date" ObjectType="{x:Type src:DateTime}"/>
</Window.Resources>
<Grid>
<TextBox Text="{Binding Source={StaticResource date},
Path=Now, Mode=OneWay}" />
</Grid>
</Window>
回答by SLaks
You cannot bind to a static property.
您不能绑定到静态属性。
You need to create a class with a property that returns DateTime.Now
, and raise the PropertyChanged
event either every day or every second. (using a timer)
您需要创建一个具有返回属性的类DateTime.Now
,并PropertyChanged
每天或每秒引发事件。(使用定时器)
回答by biju
I think you are looking to do this in code behind.Create a Property of the in your class and set binding to that property
我认为您希望在后面的代码中执行此操作。在您的类中创建一个属性并将绑定设置为该属性
public DateTime Date { get; set; }
public Window9()
{
InitializeComponent();
Date = DateTime.Now;
DataContext=this;
txt.SetBinding(TextBlock.TextProperty, new Binding("Date"));
}