Reputation: 1410
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?
Upvotes: 0
Views: 1112
Reputation: 678
In fact you can do this in XAML only with help of ObjectDataProvider. See: https://learn.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>
Upvotes: 2
Reputation: 4002
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>
Upvotes: 1