WPF GridViewColumnHeader.Click - 获取 ItemsSource

WPF GridViewColumnHeader.Click - Get ItemsSource

我有一个 WPF 页面,其中有几个 ListViews。 我想在单击 headers 时对列表进行排序,这没有问题,但是现在我为每个 ListView 创建一个单独的函数,我想创建一个通用函数。

假设我想替换它:

contexte.ListeDesAssemblagesView.SortDescriptions.Clear();
contexte.ListeDesAssemblagesView.SortDescriptions.Add(monsort);

通过类似的方式:

sender.ItemsSource.SortDescriptions.Clear();
sender.ItemsSource.SortDescriptions.Add(monsort);

编辑:这是我的功能代码,感谢 mm8。

void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e)
{
    GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
    ListSortDirection direction;
    ListView listView = sender as ListView;
    ICollectionView view = CollectionViewSource.GetDefaultView(listView.ItemsSource);

    string header = "";
    if (headerClicked.Column.DisplayMemberBinding != null)
    {
        header = ((System.Windows.Data.Binding)headerClicked.Column.DisplayMemberBinding).Path.Path;
    }
    else
    {
        try
        {
            DataTemplate cellTemplate = headerClicked.Column.CellTemplate;
            Grid grid = cellTemplate.LoadContent() as Grid;
            TextBlock textBlock = grid.Children.OfType<TextBlock>().FirstOrDefault();
            header = BindingOperations.GetBinding(textBlock, TextBlock.TextProperty).Path.Path;
        }
        catch
        {

        }
    }

    string lastHeaderName = view.SortDescriptions[0].PropertyName;
    string lastDirection = view.SortDescriptions[0].Direction.ToString();
    if (headerClicked != null)
    {
        if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
        {
            if (header != lastHeaderName)
            {
                direction = ListSortDirection.Ascending;
            }
            else
            {
                if (lastDirection == "Ascending")
                {
                    direction = ListSortDirection.Descending;
                }
                else
                {
                    direction = ListSortDirection.Ascending;
                }
            }
            if (header != "")
            {
                SortDescription monsort = new SortDescription(header, direction);
                view.SortDescriptions.Clear();
                view.SortDescriptions.Add(monsort);  
            }
        }
    }
}

如果您将事件处理程序连接到 XAML 标记中的 ListViews,如下所示:

<ListView GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler">

...您可以简单地转换 sender 参数:

void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e)
{
    ListView listView = sender as ListView;
    ICollectionView view = CollectionViewSource.GetDefaultView(listView.ItemsSource);
    //...
}