Need to format a string in a ListView GridView in code behind. XAML is not an option as the data and columns are created in code.
The XAML version of the desired date format is:
<TextBlock TextWrapping="NoWrap" Text="{Binding Path=DateTime, Mode=OneWay, StringFormat={}{0:yyyy/MM/dd hh:mm tt}}" />
In this case I cannot use XAML as the number of columns varies and the columns that need to display a date in that format varies. I just cannot figure out how to apply that date format in code behind. Below is working code behind to build the columns.
GridViewColumn gvc;
GridViewColumnHeader gvch;
Binding gvBinding;
DataTemplate template;
FrameworkElementFactory textblock;
// Data Column
gvc = new GridViewColumn();
gvch = new GridViewColumnHeader();
gvch.Content = SF.DispName;
gvch.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch;
gvch.VerticalContentAlignment = System.Windows.VerticalAlignment.Bottom;
gvch.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
gvc.Header = gvch;
gvBinding = new Binding();
gvBinding.Mode = BindingMode.OneWay;
gvBinding.Path = new PropertyPath("[" + (sDocBaseResultDocsFieldsIndex * 2).ToString() + "]");
template = new DataTemplate();
textblock = new FrameworkElementFactory(typeof(TextBlock));
textblock.SetValue(TextBlock.TextProperty, gvBinding);
// textblock.SetValue(TextBlock.TextTrimmingProperty, TextTrimming.WordEllipsis);
template.VisualTree = new FrameworkElementFactory(typeof(Grid));
template.VisualTree.AppendChild(textblock);
gvc.CellTemplate = template;
gvSrchResultsScore.Columns.Add(gvc);
sDocBaseResultDocsFieldsIndex++;
What I need to add is something like below but cannot figure it out. I have tried every permutation of {}{0:yyyy/MM/dd hh:mm tt}} that I can think of.
if (sDocBaseResultDocsFieldsIndex == 12) gvBinding.StringFormat = "Help";
The empty braces
{}that you use in the xaml are an escape sequence so the format is not interpreted as a markupextension by the parser. You don’t need them in the codebehind – try this: