I am trying to get date format as "MM/dd/yyyy", however, the current date format is coming with time too, I tried to format it with the following codes, however it is not changing, could you please correct me as follows:
<DataGridTextColumn Header="Bill Date" Binding="{Binding BillDate, StringFormat={}{0:MM/dd/yyyy}}" Width="90" IsReadOnly="True" />
and
<DataGridTemplateColumn Header="Bill Date" Width="90">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Label Content="{Binding BillDate}" ContentStringFormat="MM/dd/yyyy" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
my property code is as follows:
Property BillDate As Date
Get
Return _BillDate
End Get
Set(Value As Date)
If Not _BillDate = Value Then
_BillDate = Value
NotifyPropertyChanged("BillDate")
End If
End Set
End Property
I dont want to correct at property level, I only want to display the format at XAML, the above format is not working although it is correct to my knowledge.
EDIT:
After many trails and few experients, I came to know that the solution is not building any new code. So, the problem now is - new, modified xaml is not getting built. Could you please help me in this.
Try
"{Binding BillDate, StringFormat=d}"
which should give you month/day/year as output.
Update
The control Label's Content property is of type object and does not apply formatting like a string does. Here are your options,
Use the ContentStringFormat property on the label:
<Label ContentStringFormat="d">
<system:DateTime>2015/3/4 13:6:55</system:DateTime>
</Label>
Or the TextBox control, the Text property is a string and it takes formatting parameters.
The type of your property should be DateTime, not Date:
Property BillDate As DateTime
...
End Property
Then this works:
<Label Content="{Binding BillDate}" ContentStringFormat="MM/dd/yyyy"/>
But you might perhaps better use a TextBlock instead of a Label:
<TextBlock Text="{Binding BillDate, StringFormat=MM/dd/yyyy}"/>
Related
I have bound a ComboBox to a list of DateTime values to select a start time for an event. I am using an ItemTemplate to specify the formatting of the DateTime in the list. I also want the user to be able to manually specify a start time not in the list, like 8:27 AM or 9:30 PM.
Wiring that up is not the issue; rather, I want the user to be presented with the same formatted DateTime as the list.
<ComboBox x:Name="StartTimeButton"
ItemsSource="{Binding DataContext.StartTimes,
RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
SelectedItem="{Binding DefaultStartTime}"
IsEditable="True">
<ComboBox.ItemTemplate>
<DataTemplate>
<Label>
<TextBlock Text="{Binding StringFormat='{}{0:hh:mm tt}'}" />
</Label>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
This results in:
I have been unable to determine how to format the top TextBlock used by the ComboBox (when editing is enabled) to match the formatting of the dropdown area.
The ultra shorthand that gets you halfway there (you can drop the DataTemplate):
<ComboBox ItemsSource="{Binding Times}"
IsEditable="True" ItemStringFormat="hh:mm tt"
TextSearch.TextPath="Hour"/>
The problem is, that DateTime has no property that outputs the time in that format. Personally, i would write a wrapper that has an internal DateTime and a property that facilitates formatting to string and parsing from it.
There does not appear to be a standard way of creating a new item form the entered text, so you might need to parse the ComboBox.Text manually in case a value is entered that is not in the list.
Inside my window, I have a simple datagrid control with a dateTimePicker column, and a textbox column. I group the rows inside the datagrid by a month-year string derived from the dateTimePicker. Here is the xaml for the columns and the grouping.....
<DataGridTemplateColumn Header="Date" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<xctk:DateTimePicker IsEnabled="True" Format="Custom" FormatString="M/d/yyyy h:mm" Value="{Binding theDate, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Text" Width="150">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox TextWrapping="Wrap" AcceptsReturn="True" MaxLines="2" VerticalScrollBarVisibility="Auto" MaxLength="150" Text="{Binding theText, UpdateSourceTrigger=LostFocus, Mode=TwoWay}"></TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}" FontWeight="Bold" Padding="3"/>
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</DataGrid.GroupStyle>
I have a very simple class with the text string, and datetimepicker datetime, and a string for month-year that I create dynamically. Here is the C# code for the class...
public DateTime dueDate { get; set; }
public String task { get; set; }
private String _monthYear;
public String monthYear
{
get { return dueDate.Month.ToString() + " - " + dueDate.Year.ToString(); }
}
Here is my initialization of the grouping
myCollectionView = CollectionViewSource.GetDefaultView(myObservableCollectionList);
myCollectionView.GroupDescriptions.Add(new PropertyGroupDescription("monthYear"));
MyDataGrid.ItemsSource = myCollectionView;
// In this case, myObservableCollectionList is an observable collection that holds the datagrid
// rows. myCollectionView is an ICollectionView object
Everything is working properly except one very annoying piece of unexpected behavior. I don't know if this is a bug with the DateTimePicker control from the extended WPF toolkit.
Whenever I change the month or year on the DateTimePicker control and click on a new row or a different column in the same row, the row where I changed the date will not be grouped but will remain inside the old month-year date group until I sort it. This behavior would be fine if it was consistent HOWEVER...
If i were to change the month or year on the DateTimePicker control, and then tab through or click through the same DateTimePicker control (Not changing anything), and then click on a new row, the old row will be grouped into a new month - year category.
I'm not sure but I feel like this is a bug with the DateTimePicker control where it's calling some sort of event when you tab through the control even if you don't change date. However right now I'm pretty confused, and was wondering if anyone has any insight as to why this is happening.
*NOTE** I have tested this with and without the INotifyPropertyChanged, I do have the interface implemented, and the behavior occurs with and without it implemented I thought I would just leave it out for simplicity sake.
Any help is appreciated thank you!
I have fixed this issue, it was caused by the uses of both a _monthYear as well as a monthYear, so I guess whenever i would change the date, there would be multiple calls to change _monthYear. For whatever reason, I'm assuming something to do with the group description...
taskScheduleCollection.GroupDescriptions.Add(new PropertyGroupDescription("monthYear"));
maybe mixed in with the ValueChanged or a similar event inside the DateTimePicker would cause the grouping to re apply and new row groups would be created(I'm not 100% sure about this).
I fixed this issue by just removing the _monthYear property as it was unnecessary and just keeping a single monthYear property that was dependent on the date.
public String monthYear
{
get { return _date.Month.ToString() + " - " + _date.Year.ToString(); }
}
The grouping now only reapplys whenever i sort my list collection, which is the consistent behavior that I want.
Trying to format a datetime bound value in my XAML using Silverlight 5 like so:
<TextBlock Text="{Binding ContactDate, Mode=OneWay, StringFormat={}{0:'dd/MM/yyyy'}}" Margin="5,0" />
I'm getting the following error:
Unexpected Token after end of Markup Extension.
This is driving me insane!
Try:
Text="{Binding ContactDate, Mode=OneWay, StringFormat='{}{0:dd/MM/yyyy}'}"
Unless you mean that you want singlequotes before and after the date string.
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 ...}"
We are binding an unknown result set to a WPF DataGrid at run time. Some of our columns are going to contain DateTime values and we need to properly format these date time fields. Without knowing which columns are going to be DateTime fields at design time, how are we able to format the columns at runtime?
We are using a DataTable's DefaultView to bind to the WPF DataGrid.
Format the binding by StringFormat:
<DataGridTextColumn Header="Fecha Entrada"
Width="110"
Binding="{Binding EnterDate, StringFormat={}\{0:dd/MM/yyyy hh:mm\}}"
IsReadOnly="True" />
I think it's better than writing code behind pieces of code
I figured out how to do this in code...hopefully there is a way to mimic this in XAML. (Please post if you find a working XAML sample.)
To accomplish this in code, add an event handler for the Grid's AutoGeneratingColumn event, such as:
private void ResultsDataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyType == typeof(DateTime))
{
DataGridTextColumn dataGridTextColumn = e.Column as DataGridTextColumn;
if (dataGridTextColumn != null)
{
dataGridTextColumn.Binding.StringFormat = "{0:d}";
}
}
}
Hey you can set the locale culture info in the constructor of the WPF form as
this.Language = XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag);
Or you can include the xml markup xml:lang="en-GB" in the window header markup
<DataGridTextColumn Header="Last update"
Width="110"
IsReadOnly="True"
Binding="{Binding Path=Contact.TimeUpdate, StringFormat={}\{0:dd/MM/yyyy hh:mm\}, Mode=OneWay}" />
I would use a DataTemplate with a DataType of Date or DateTime (depending on which it will come through as). Place a TextBlock in the DataTemplate with a StringFormat in the binding.
Something like this should work (untested)
<DataTemplate DataType="{x:Type DateTime}">
<TextBlock Text="{Binding StringFormat={0:d}}" />
</DataTemplate>
Or if you want it to apply just in the Grid
<wpfToolkit:DataGrid>
<wpfToolkit:DataGrid.Resources>
<DataTemplate DataType="{x:Type DateTime}">
<TextBlock Text="{Binding StringFormat={0:d}}" />
</DataTemplate>
</wpfToolkit:DataGrid.Resources>
...
</wpfToolkit:DataGrid>
dataGridTextColumn.Binding.StringFormat = "{0:dd/MM/yyyy}";
worked beautifuly
i run this way. its work complete .
<TextBlock Text="{Binding Date_start, StringFormat=\{0:dd-MM-yyyy\}, Mode=OneWay}" />
The answer of FarrEver, May 11 is good, but by me it doens't function. i still get American mm/dd/yyy instead my German dd/mm/yyyy. So I propose to find the regional settings of computer and use it in StringFormat
Private Sub DGrid_AutoGeneratingColumn(ByVal sender As System.Object, ByVal e As Microsoft.Windows.Controls.DataGridAutoGeneratingColumnEventArgs)
If e.PropertyType Is GetType(DateTime) Then
Dim dataGridTextColumn As DataGridTextColumn = TryCast(e.Column, DataGridTextColumn)
If dataGridTextColumn IsNot Nothing Then
Dim ShortDatePattern As String = System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern
dataGridTextColumn.Binding.StringFormat = "{0:" + ShortDatePattern + "}" '"{0:dd/MM/yyyy}"
End If
End If
End Sub
see also: my blog