Silverlight Datagrid Numeric Sort
Is there simpler way to correctly sort numeric data in a datagrid?
Explanation - When you click on a column header with data 1,5,10,2 it sorts it as text (1,10,2,5).
I have read that you can implement ICollectionView开发者_开发技巧, to create your own custom sorting. Before I go down that path, I want to make sure there isn't an easier way.
A co-worker solved my problem. By wrapping the source object in a wrapper, you can then define a SortBLANK, which just returns the data as int instead of string. I then use SortMemberPath to set the sorting for that call. Note, this only works for the problem of numeric only sorting.
XAML(Partial):
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Header="MAC" FontSize="12" Binding="{Binding macaddr}" Width="100"/>
<sdk:DataGridTextColumn Header="Upload Rate" SortMemberPath="SortUpload" FontSize="12" Binding="{Binding uploadRate}" Width="3*"/>
<sdk:DataGridTextColumn Header="Download Rate" SortMemberPath="SortDownload" FontSize="12" Binding="{Binding downloadRate}" Width="3*"/>
</sdk:DataGrid.Columns>
Code-Behind(Partial):
public class OnlineDevicesWrapper
{
public string macaddr{get;set;}
public string uploadRate { get; set; }
public string downloadRate { get; set; }
public int SortUpload
{
get
{
return int.Parse(uploadRate);
}
}
public int SortDownload
{
get
{
return int.Parse(downloadRate);
}
}
}
What you want is a natural string sort comparer, using the IComparer interface. There are several C# solutions out there, I've listed a few. Note that I don't think any of them are geared towards Silverlight specifically, though you shouldn't have too much trouble using them in Silverlight.
How to achieve Natural(human alpha-numeric ) Sorting, for silverlight datagrids using ViewModel?
http://www.codeproject.com/KB/string/NaturalSortComparer.aspx
Natural Sort Order in C#
http://www.codeproject.com/KB/recipes/csnsort.aspx
精彩评论