即使在排序后,如何始终将 DataGrid 的一行或多行保持在顶部

hel*_*ker 5 c# sorting wpf datagrid

我有一个绑定到 ObservableCollection(在 ViewModel 上)的 DataGrid(在视图上)。

对于这个 ObservableCollection,我以编程方式添加了一个“魔术行”,因为所选项目将用于对其他地方的另一个集合进行排序,并且我添加了这个虚拟行来“清除”过滤。

目前,当视图加载时,我的魔法字符串总是出现在顶部(因为我将它插入到 index 0),但是一旦我点击标题更改排序顺序,行就会按字母顺序重新排列,我的魔法行就会丢失在废墟中.

我想要的是魔术行始终出现在顶部,即使我单击标题更改排序顺序也是如此。

视图模型:

// (...)

public ObservableCollection<FilteringItem> ItemTypes
{
    get
    {
        var result = new ObservableCollection<FilteringItem>(_setups.Select(n => n.ItemType)
                                                             .Distinct()
                                                             .Select(s => new FilteringItem(s, s))
                                                             .OrderBy(v => v.Name));


        // Magic Happens Here: adding a "magic" row to remove filtering
        // (that is, "allow all") when used by some filtering method elsewhere;
        string allString = String.Format("All ({0})", result.Count);
        var filteringAll = new FilteringItem(allString, "");

        result.Insert(0, filteringAll);

        return result;
    }

}
// (...)

public class FilteringItem
{
    public string Name { get; private set; }
    public string Value { get; private set; }

    public FilteringItem(string name, string val)
    {
        Name = name;
        Value = val;
    }
}    
Run Code Online (Sandbox Code Playgroud)

看法:

<DataGrid ItemsSource="{Binding ItemTypes}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Tipo" Width="*" Binding="{Binding Name}"/>
    </DataGrid.Columns>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

hel*_*ker 1

感谢这篇博文,我已经让它可以工作了。

“秘密”是拦截Sorting事件(设置e.Handledtrue),然后将 DataGrid.ItemsSource 转换为ListCollectionView,然后将自定义分配IComparerListCollectionView.CustomSort属性。

然后,在排序时,您以某种方式识别固定行(在我的例子中通过空值),并使其始终位于顶部(这又取决于ListSortDirection)。

public partial class ViewContainingDataGrid : UserControl
{
    public ViewContainingDataGrid()
    {
        this.InitializeComponent();
    }

    private void datagrid_Sorting(object sender, DataGridSortingEventArgs e)
    {
        e.Handled = true;
        SmartSort(sender, e.Column);
    }

    private void SmartSort(object sender, DataGridColumn column)
    {
        ListSortDirection direction = (column.SortDirection != ListSortDirection.Ascending) ?
                             ListSortDirection.Ascending : ListSortDirection.Descending;

        column.SortDirection = direction;
        var dg = sender as DataGrid;
        var lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(dg.ItemsSource);
        lcv.CustomSort = new SmartSorter(direction);
    }

}

public class SmartSorter : IComparer
{
    public ListSortDirection Direction { get; private set; }

    public SmartSorter(ListSortDirection direction)
    {
        Direction = direction;
    }


    public int Compare(object x, object y)
    {
        string valorx = x as string;
        string valory = y as string;

        int comparison = valorx.CompareTo(valory);
        if (Direction == ListSortDirection.Descending)
            comparison *= -1;

        // Override the sorting altogether when you find the special row value
        if (String.IsNullOrWhiteSpace(valorx))
            comparison = -1;
        else
        if (String.IsNullOrWhiteSpace(valory))
            comparison = 1;

        return comparison;
    }
}
Run Code Online (Sandbox Code Playgroud)