wpf 数据网格自定义列排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15292688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wpf data grid custom column sorting
提问by Roman A. Taycher
How do I add a special sorting method to a particular column to allow different types of sorting(such as sorting 120.5.1.50 in between 120.5.1.12 and 120.5.1.110 instead of having 120.5.1.110 be the lowest value.
如何向特定列添加特殊排序方法以允许不同类型的排序(例如在 120.5.1.12 和 120.5.1.110 之间对 120.5.1.50 进行排序,而不是将 120.5.1.110 设为最低值。
Also how do I allow click header sorting of a custom type bound it a template column. Is this even possible?
另外,我如何允许自定义类型的单击标题排序将其绑定到模板列。这甚至可能吗?
回答by failedprogramming
You can implement IComparer and define your own comparing logic.
您可以实现 IComparer 并定义您自己的比较逻辑。
public class MyComparer : IComparer<Object>
{
public int Compare(Object stringA, Object stringB)
{
// Your logic here
}
}
After you can just use LINQ OrderBy method with your custom comparer.
在您可以将 LINQ OrderBy 方法与您的自定义比较器一起使用之后。
items = items.OrderBy(x => property, comparer).ToList();
Refer to this link.
请参阅此链接。
EditTO override the default sorting behaviour of a WPF Datagrid, refer to the answer in this link.
编辑要覆盖 WPF 数据网格的默认排序行为,请参阅此链接中的答案。
回答by trilson86
If you want to maintain the custom sort order after clicking the column header, you can use an attached behaviour. I came up with this solution which seems to work well:
如果要在单击列标题后保持自定义排序顺序,可以使用附加行为。我想出了这个似乎运行良好的解决方案:
WPF DataGrid CustomSort for each Column
This is an MVVM solution - there are probably simpler ways of doing this if you want to delve into the world of code-behind.
这是一个 MVVM 解决方案 - 如果您想深入研究代码隐藏的世界,可能有更简单的方法可以做到这一点。

