如何对名为“评论”的列中的值进行自定义排序? 列中的值将包含以“.”结尾的前缀。和索引号。因此,例如,单元格中将包含值“N1.1”,其中“N1” - 是前缀,“1” - 是标识号。
数字按顺序排列: N1.0、N1.1、N1.2、N1.3、N1.4、N1.5。 N1.6、N1.7、N1.8、N1.9、N1.10、N1.11等
现在得到:N1.1、N1.10、N1.11、N1.2、N1.3、N1.4、N1.5。 N1.6、N1.7、N1.8、N1.9.
在名为“MechanicScheduleView.xaml”的视图中,我有一个 DataGrid:
<DataGrid Grid.ColumnSpan="2" CanUserReorderColumns="False" dp:DataGridColumnsBehavior.BindableColumns="{Binding ColumnCollection}" ItemsSource="{Binding Path=Datatable}" AutoGenerateColumns="False" IsReadOnly="True"/>.
在名为 MechanicScheduleViewModel 的视图模型中,我有一个分配给 ItemSource 的 propertyDataTable 数据表:
public DataTable Datatable
{
get
{
return _datatable;
}
set
{
if (_datatable != value)
{
_datatable = value;
}
OnPropertyChanged();
}
}
在名为 MechanicScheduleViewModel 的视图模型中,我还有一个属性 ObservableCollection ColumnCollection ,它被分配给 BindableColumns (我动态更改列数)
public ObservableCollection<DataGridColumn> ColumnCollection
{
get
{
return this._columnCollection;
}
set
{
_columnCollection = value;
OnPropertyChanged();
}
}
DataGrid 正确显示数据表中的所有值,但不幸的是我无法设置列值的自定义排序。
您不应该处理诸如以下之类的控件:
DataGridColumn
在您的视图模型类中。相反,如果您需要动态列,请使用 DataTable
作为数据源。这样数据处理就更容易、更直观。
要实现自定义排序,您可以为要执行自定义排序的列创建自定义数据类型。然后让这个类型实现
IComparable
(example)来为类型/表列提供自定义排序。DataTable
施加了一些限制(来源:DataColumn.DataType 属性/备注):
CommentData.cs
class CommentData : IComaparable<string>
{}
示例
var dataTable = new DataTable();
var customSortCommentColumn = new DataColumn("Comment", typeof(object));
dataTable.Columns.Add(customSortCommentColumn);
// Sort the table by the custom sort column in ascending order
dataTable.DefaultView.Sort = "Comment ASC";
// Sort the table by the custom sort column in descending order
dataTable.DefaultView.Sort = "Comment DESC";