简体   繁体   中英

Xaml DateTime binding

I am binding DateTime in a TextBlock like so:

<TextBlock 
    HorizontalAlignment="Center" 
    Text="{
        Binding Source={x:Static sys:DateTime.Today}, 
        StringFormat='{}{0:dddd, MMMM dd, yyyy}'
    }"
/>

Is there a way to do the same binding but for 10 days in the past and not for today's date?

Add a static class like this:

namespace MyWpfApplication
{
    public static class MyDateTime
    {
        public static DateTime TenDaysAgo => System.DateTime.Now.AddDays(-10);
    }
}

Then use it in your XAML (don't forget to add an xml namespace):

<Window x:Class="MyWpfApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MyWpfApplication">
    <TextBlock
        HorizontalAlignment="Center"
        Text="{
            Binding Source={x:Static local:MyDateTime.TenDaysAgo},
            StringFormat='{}{0:dddd, MMMM dd, yyyy}'
        }"
    />
</Window>

In fact you can do this in XAML only with help of ObjectDataProvider. See: https://docs.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-bind-to-a-method

<StackPanel>
    <StackPanel.Resources>
        <ObjectDataProvider x:Key="tod" ObjectInstance="{x:Static sys:DateTime.Today}" MethodName="AddDays">
            <ObjectDataProvider.MethodParameters>
                <sys:Int32>-10</sys:Int32>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </StackPanel.Resources>
    <TextBlock  HorizontalAlignment="Center"  Text="{Binding Source={StaticResource tod},  StringFormat='{}{0:dddd, MMMM dd, yyyy}'}"/>
</StackPanel>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM