Sort WPF datagrid with integer appended with string

我是研究僧i 提交于 2019-12-01 09:32:01

问题


I have a wpf datagrid. I assign ObservableCollection to it.

DG1.DataContext = a; 

One of the columns is having values like following

1_A_B
12_A1_B
3_A2_B
10_A3_B
2_A4_B
15_A5_B

i want to sort the datagrid using the first integer value like following

1_A_B
2_A4_B
3_A2_B
10_A3_B
12_A1_B
15_A5_B

If i sort using this column, it is taking as string ascending like following(which is not i want)

1_A_B
10_A3_B
12_A1_B
15_A5_B
2_A4_B
3_A2_B

I want to sort using the first integer value in above column


回答1:


The values 1_A_B, 12_A1_B etc will be contained within the property bound to that column. Let's call this PropertyA.

Possibly the easiest way to achieve this is to have another property on the data object, let's call that YourSortOrder. When the setter on PropertyA gets called with a non null value, you can use simple string manipulation together with an int.Parse() to extract the numeric value and assign it to YourSortOrder.

This code isn't production quality but illustrates the point:

public string PropertyA
{
    get { ... }
    set
    {
        _propertyA = value;
        if (value != null)
            YourSortOrder = int.Parse(value.Substring(0, value.IndexOf("_", StringComparison.InvariantCultureIgnoreCase)));
    }
}

then set the SortMemberPath of your DataGridColumn to the property YourSortOrder:

<DataGridColumn x:Name="xxxxx"
                SortMemberPath="YourSortOrder" 
                ...etc...


来源:https://stackoverflow.com/questions/22660847/sort-wpf-datagrid-with-integer-appended-with-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!