I have a model that and a file size as Long property. I am displaying the size in the field and converting it to a human friendly file size (i.e. KB, MB, GB, etc.) instead of just a number.
<igDp:Field Name="Size" Label="Size" Converter="{StaticResource diskSizeConvert}"> <igDp:Field.Settings> <igDp:FieldSettings AllowEdit="False" EditAsType="sys:String"/> </igDp:Field.Settings> </igDp:Field>
And Converter class:
[ValueConversion(typeof(long), typeof(string))] public class DiskSizeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return FileSystemUtils.ToHumanReadableDiskSize((long)value); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } }
Field is read only (i.e. user is not allowed to edit it in the grid).
When sorting, the field is sorted by the text value (i.e. KB, MB, etc.) instead of the Long property. How can I get the sorting working properly?
Hello Mensur,
Thank you for contacting Infragistics.
Fields in the XamDataGrid have the ability to apply a custom sort via their Field.Settings.SortComparer property. This property takes an IComparer derived class, when implemented will allow you to compare the values and preserve the sort.
You can read more about sorting via a custom IComparer here: https://www.infragistics.com/help/wpf/xamdatagrid-sorting-and-grouping-process-overview.
If you cast the objects in the IComparer's Compare method to your numeric type, you can obtain the absolute value and use the built-in CompareTo method to return the correct value to the IComparer's Compare method.
I attached a sample below to help you get started. Let me know if you have any questions.
XDGAbsoluteValueSortCase.zip
Would this not require me to convert a string value of 25.6 MB to actual byte size and therefore lose precision since I am limiting the size to a single decimal place? As mentioned, I have a Size property that is of type Long with example value of 26,355. I am trying to display it in the grid as human readable size (i.e. 25.6 MB) using the provided converter but keep the underlying Size property intact with value of 26,355 and use it for sorting. Maybe my Converter approach is not correct in this case. How can I accomplish what I want?
Hello Mensure,
Thank you for following up. I recommend using a TextField, instead of just Field, and applying your converter to the ValueToDisplayTextConverter property (directly on the field).
eg.
<igDP:TextField Name="Name" ValueToDisplayTextConverter="{StaticResource DiskSizeConverter}" EditAsType="sys:Long"> </igDP:TextField>