开发者

wpf,How to bind Current Date?

I have a TextBlock control to which I would like to bind current System Date , how can I do that by Code Behind ?

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.

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

  Binding bd = new Binding("System.DateTime.Now");
        bd.Source = this;
        te开发者_C百科xtBox.SetBinding(TextBox.TextProperty, bd);

Thanks for help


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}'}"/> 


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.

<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>


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)


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"));
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜