Custom DateTime stringformat in WPF - wpf

I can't get my custom DateTime string format to work in my binding. I want the format to be "mmmm, yyyy" (e.g. "June, 2012").
The following does not work. I get a short date format (m/d/yyyy).
<TextBlock Text="{Binding ElementName=ThisWindow,
Path=Date,
StringFormat={}{0:MMMM\, yyyy}"/>
I've considered using a converter, but I prefer a pure XAML approach.
Edit:
For clarity, I have a Window with a dependency property Date of type DateTime. In my XAML, I've named the window 'Thiswindow'.
Edit 2:
I looked back at my actual code, and I had a Label, not a TextBlock. I changed it to TextBlock and it works fine.
<Label Content="{Binding ElementName=ThisWindow,
Path=Date,
StringFormat={}{0:MMMM\, yyyy}"/>
Anyone know why it doesn't work with Label?
Thanks.

ContentControls have a ContentStringFormat property which overrides the original formatting.
(When i saw your question i expected this to be the problem actually but was surprised to find a TextBlock at first)

Your month needs to be in uppercase:
{Binding Source={x:Static sys:DateTime.Now}, StringFormat={}{0:MMMM\, yyyy}}
EDIT:
The Label problem is probably because Label has Content, not Text.
Change the Text="{Binding ...}" to Content="{Binding ...}"

Related

WPF DatePicker show DateTime.Today OR Binding

What is the best way to have a WPF DatePicker show a predefined DateTime (e.g. DateTime.Today) while still maintaining binding?
SelectedDate="{x:Static sys:DateTime.Today}"
and
Text="{Binding Path=MyPublicProperty.ADateTimeMemberProperty, Mode=TwoWay}"
don't play well together. When a UserControl is loaded, I'd like it to display today's date, until a row is selected. Is there a way to make them get along?
Text="{Binding Path=MyPublicProperty.ADateTimeMemberProperty,
Mode=TwoWay, FallbackValue={x:Static sys:DateTime.Today}}"
Use FallbackValue to set a value when it cannot be retrieved from the binding.

Date in WPF listbox not displaying in correct locale

I have a XAML page with a ListBox bound to a collection of Customer objects. The Customer class has a CreatedDate property which is bound to a TextBox within the ListBoxItem template. For some reason the date is appearing in US format (I'm in the UK), despite adding this known fix to App.xaml:-
FrameworkElement.LanguageProperty.OverrideMetadata(
typeof(FrameworkElement),
new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
Dates elsewhere on the page are being formatted correctly. Any ideas?
Update:- the date in the ListBoxItem template is being displayed like this:-
<TextBlock>
<TextBlock.Inlines>
<Run Text="{Binding CreatedDate}"/>
...various other <Run elements ...
</TextBlock.Inlines>
</TextBlock>
This seems to be where the problem lies. If I bind the CreatedDate using a plain instead of in the construct (i.e. <TextBlock Text="{Binding CreatedDate}"/>), it formats correctly. Why would this be? Is it a bug with the Inlines element?
This has also been reported to be a bug in the Microsoft Forums (although there is no link to a bug report). Per Mike Danes, a moderator in the forum:
The problem is the Run element, this is not a FrameworkElement,
it's a FrameworkContentElement.
Its language property was registered with a default value of en-US
and it cannot be overriden.
In the meantime, you could work around this by setting the language right on the run (this is suggested in the MS forum, but I have not tried it myself).
Another alternative, if you know that you alsways want a specific format, is to use the StringFormat option in the binding:
<TextBlock>
<TextBlock.Inlines>
<Run Text="{Binding CreatedDate, StringFormat={}{0:dd/MMM/yyyy}}"/>
...various other <Run elements ...
</TextBlock.Inlines>
</TextBlock>
Note that the StringFormat option for ShortDate does not work - you need to put in an explicit format:
<TextBlock>
<TextBlock.Inlines>
<Run Text="{Binding CreatedDate, StringFormat=d}"/>
...various other <Run elements ...
</TextBlock.Inlines>
</TextBlock>

Bind TextBlock text when it is more then a simple string

I have a textblock and I would like to bind its content to a property in my viewmodel. This is fine if the content is a simple string. But it's no so fine if I want to format the content and use or tags... In this case I cannot bind a string: the textblock would simply display a string like this "Hallo".
Any ideas ? Thanks
if you have a property of some type - you can create a datatemplate for this type
<DataTemplate DataType="{x:Type local:MySomeType}">
<!--your visual presentation goes here-->
</DataTemplate>
now you can simply use a ContentPresenter to show your property
<ContentPresenter Content="{Binding MySomeTypeProperty}"/>
See what the StringFormat property can do for you. If that is not sufficient, you might want to write a binding converter.
Something like this:
<Textblock content="{Binding MyProperty, StringFormat={}Hello {1}}" />
Just got to play with the string format.

How to set TextSearch.Text for a combobox whose TextBlock uses converter?

In the below code, Combobox is wired to NameInfo object along with a converter.NameInfoConverter returns a format in which items in combobox are shown in a particular format (for eg: LastName, FirstName (Badge#) )
Now, when I set TextSearch.Text="{Binding NameInfo, Converter={StaticResource NameInfoConverter}, ConverterParameter=true}" on combobox; TextSearch doesn't work. When I set TextSearch.TextPath="Name", search itself works but doesnot get the correct format displayed in the selectionbox of combobox.
Any Ideas?
<StackPanel>
<ComboBox x:Name:"cmbName">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name,
Converter={StaticResource NameInfoConverter}, ConverterParameter=true}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
You've probably hit a limitation in the API. I suggest you take an alternative route and bind directly to a property that is correctly formatted for your textblock.
If this is a serious app, you may want to look into using the MVVM pattern and place your converted/formatted property in the viewmodel. Otherwise, just create a new property on your databound class called NameInfo or something and do the conversion from that.

How to change date format in Silverlight DatePicker control?

This works great:
<my:DatePicker IsTodayHighlighted="True" Width="200">
</my:DatePicker>
But I want to format the date, something like this:
<my:DatePicker IsTodayHighlighted="True" Width="200" Format="yyyy-mm-dd">
</my:DatePicker>
Anyone know the syntax for this?
Unfortunately the DatePicker control currently does not support free DateTime formats.
If this is something you're interested in seeing up support in future version of DatePicker, please create a codeplex feature request that suggests that.
http://silverlight.codeplex.com/WorkItem/Create.aspx
Just to point out that the new Silverlight Toolkit March 2009 TimePicker & TimeUpDown controls do support a full range of globalization options. One of those include free DateTime formats. So it is just a matter of public interest on whether or not we port that ability back to DatePicker.
Have a look at the format for TimePicker #
http://silverlight.codeplex.com/Wiki/View.aspx?title=Silverlight%20Toolkit%20Overview%20Part%201#TimePicker
In the meanwhile, The best workaround is to either change the local culture or the format on the local culture.
public App()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-NL");
or change the format on the local culture.
public App()
{
Thread.CurrentThread.CurrentCulture = (CultureInfo) Thread.CurrentThread.CurrentCulture.Clone();
Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "D/m/yyyy";
You should define a custom control template and edit the textbox of the datepicker control to format the text.
The Silverlight DatePicker has a SelectedDateFormat Property on it, this may be what you are looking for.
You could just hide the controls textbox (with a smaller width), expose you're own (optionally set the IsEnabled to false) and use an Element binding and Converter. If you're using MVVM, then set the DataContext to your ViewModel. I suppose another option would be to overwrite the DataTemplate to not include the text box and do the same idea.
<StackPanel Orientation="Horizontal" Height="22">
<TextBox x:Name="textBox2" Width="106" Text="{Binding ElementName=datePicker2, Path=SelectedDate, Mode=TwoWay, Converter={StaticResource internationalDateTimeFormatConverter}}" />
<controls:DatePicker x:Name="datePicker2" IsTabStop="False" SelectedDate="{Binding TargetDatePicker, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" Width="23" HorizontalAlignment="Left" />
</StackPanel>
UPDATE:
The TwoWay binding from the text box to the the date picker works well, but it doesn't update the ViewModel Property. So I'm going to set the IsEnabled=False and call it good.
I notice this is an answered question.
But I would like to notify about this link to a Silverlight 5 control toolkit I have recently started creating. It contains (among other controls) a DateTimeBox control in which you can handle both date and time within the same control. At this point, it is still under development, but it should be usable for most scenarios.

Resources