Wpf, How to link the current date?

I have a TextBlock control to which I would like to bind the current System date, how can I do this with code?

The goal is to display the current System date and time in this TecBlock, and I do not need to update the control all the time, only once.

I hope this is the easiest code. I do not want to create a DateTime property. follow is my code: it is not true that it cannot find BindSource

  Binding bd = new Binding("System.DateTime.Now");
        bd.Source = this;
        textBox.SetBinding(TextBox.TextProperty, bd);

thanks for the help

+3
source share
4 answers

Shows 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}'}"/> 
+17
source

You cannot bind to a static property.

, DateTime.Now, PropertyChanged . ( )

+2

Well, from a technical point of view, you could bind the current time, as in the example below, but without proper binding, since you can’t update it at all with the mentioned 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>
+2
source

I think you want to do this in code. Create a Property in your class and bind to this property

public DateTime Date { get; set; }
    public Window9()
    {
        InitializeComponent();
        Date = DateTime.Now;
        DataContext=this;
        txt.SetBinding(TextBlock.TextProperty, new Binding("Date"));
    }
+1
source

Source: https://habr.com/ru/post/1779094/


All Articles