Hi,
I am trying to come up with some generic way to apply Data Annotation attribute StringFormat to XAML:
[DisplayFormat(DataFormatString = "MM-dd-yyyy")]public DateTime? Date { get; set; }
It does not work automatically. For regular data grid I can do this:
private void gridMessages_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { DataGridBoundColumn obj = e.Column as DataGridBoundColumn; var attrs = Attribute.GetCustomAttributes(typeof(TestMessage).GetProperty(e.PropertyName)); var attr = attrs.FirstOrDefault(a => a is DisplayFormatAttribute) as DisplayFormatAttribute; if (obj != null && obj.Binding != null && attr != null && string.IsNullOrEmpty(obj.Binding.StringFormat)) { obj.Binding.StringFormat = attr.DataFormatString; } }
But xamGrid does not have AutoGeneratingColumn event.
Any suggestion how to insert DataFormatString into data binding for xamGrid.
Or even better, maybe xamGrid can use somehow data annotation attributes on data model for data formating?
Thanks.
Vic
If you are using a TextColumn there is a FormatString off othe column which can be used to format the string displayed.
Thanks for reply.
I have AutoGenerateColumns="True" - don't set up columns myself.
and in addition to this I am more concerned about numeric data types.
Thank you.
My mistake was that data source was not initialized before loading a xamGrid:
MyList = new List<MyObjectType>();
After adding this everything works.
Assuming you are already passed the Grid.Loaded stage, once you switch the ItemSource you should have the columns. In the sample I change the format string in the Loaded as well,
.
Thanks, it is very helpful.
I tried to use its hints and am adding columns in code in ColumnLayoutAssigned. It works nicely for AutoGenerateColumns="False".
However, I want to have columns auto-generated and add formatting in code. So, when AutoGenerateColumns="True"and ItemsSource set in XAML, in ColumnLayoutAssigned ColumnLayout does not have anything in Columns, both in grid.ColumnLoayouts[0].Columns and e.Layout.Columns.
Would you help me with this one as well please.
Attached is a sample showing how to either create a column or access a column and change the format string
Thanks Darrell.
I tried this and on this event e.ColumnLayout.Columns is empty. I have this on my grid AutoGenerateColumns="True".
I really need any way to set formatting on my columns, but they should be autogenerated.
Or, just got this idea, I can make it not autogenerated, but generate columns in code behind and set formatting there. Will it work? Can you please point to any code how to create columns and binding for them?
Thanks