Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Now in XAML without binding

Can I put the date of today in a label without binding it in XAML, something like

<Label Text="DateTime.Now, StringFormat='{0:MMMM dd, yyyy}'"/>
like image 817
Mireille Avatar asked Feb 24 '17 06:02

Mireille


People also ask

Can I use XAML datetime in WPF?

DateTime values for the existing WPF controls generally only use the date components of DateTime and not the time components. When specifying a DateTime in XAML, you can use any of the format strings interchangeably. You can also use formats and format strings that are not specifically shown in this topic.

Is it necessary to initialize a date in XAML?

Setting dates in XAML is not always necessary and may not even be desirable. For example, you could use the DateTime.Now property to initialize a date at run time, or you could do all your date adjustments for a calendar in the code-behind based on user input.

What is the short date format for a datetime in WPF?

The following shows the short date format for a DateTime in XAML: M/d/YYYY. This is the simplest form that specifies all necessary information for typical usages by WPF controls, and cannot be influenced by accidental time zone offsets versus a time component, and is therefore recommended over the other formats.

Why can’t I use datetime?

There are basically two main problems with it. First, local DateTime values don’t carry any information about time zones at all. You’d think that’s the case, based on the name, but you’d be wrong.


1 Answers

Can I put the date of today in a label without binding it in XAML

No, you can't.

For Binding, use

xmlns:sys="clr-namespace:System;assembly=mscorlib"

with

<Label Content="{Binding Source={x:Static sys:DateTime.Now}, StringFormat='{0:MMMM dd, yyyy}'}" />

Though, you can set it from Code behind like myLabelControl.Content = DateTime.Now;, but I would totally avoid this.

like image 120
Nikhil Agrawal Avatar answered Sep 19 '22 16:09

Nikhil Agrawal