WPF 中的 Icollectionview 排序和分组

2024-01-26

我在 WPF 中创建了一个 listview 控件并成功完全绑定Icollectionview的对象ObservableCollection<object>。我的列表视图列是动态创建的。 我必须对列表视图进行排序和分组,但它无法正常工作。 我的代码如下。

private void LaodList()
{
    dt = new DataTable();
    dt.Columns.Add("AA", typeof(string));
    dt.Columns.Add("BB", typeof(string));
    dt.Columns.Add("cc", typeof(string));
    dt.Rows.Add("12", "66",11);
    dt.Rows.Add("33", "44",22);
    dt.AcceptChanges();


    GridView gv = new GridView();
    //gv.AllowsColumnReorder = true;

    List<string> myItemsCollection = new List<string>();
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        GridViewColumn col = new GridViewColumn();
        col.Header = dt.Columns[i].ColumnName;
        col.DisplayMemberBinding = new Binding(string.Format("[{0}]", i));
        gv.Columns.Add(col);
        myItemsCollection.Add(col.Header.ToString());
    }

    LvItems.View = gv;
    this.Source = CollectionViewSource.GetDefaultView(LoadItems(dt)) ;  
    LvItems.DataContext = this.Source;
    cmbGroups.ItemsSource = myItemsCollection;
}


public ObservableCollection<object> LoadItems(DataTable dt)
{
    ObservableCollection<object> items = new ObservableCollection<object>();
    foreach (DataRow dataRow in dt.Rows)
    {
         items.Add(dataRow.ItemArray);
    }

    return items;
 }

//sort////////////////////////

private void ListView_Click(object sender, RoutedEventArgs e)
{

    GridViewColumnHeader currentHeader = e.OriginalSource as GridViewColumnHeader;
    if (currentHeader != null && currentHeader.Role != GridViewColumnHeaderRole.Padding)
    {
        if (this.Source.SortDescriptions.Count((item) => item.PropertyName.Equals(currentHeader.Column.Header.ToString())) > 0)
        {
            SortDescription currentPropertySort = this.Source
                        .SortDescriptions
                        .First<SortDescription>(item => item.PropertyName.Equals(currentHeader.Column.Header.ToString()));

                    //Toggle sort direction.
                    ListSortDirection direction =
                        (currentPropertySort.Direction == ListSortDirection.Ascending) ?
                        ListSortDirection.Descending : ListSortDirection.Ascending;

                    //Remove existing sort
                    this.Source.SortDescriptions.Remove(currentPropertySort);
                    this.Source.SortDescriptions.Insert(0, new SortDescription(currentHeader.Column.Header.ToString(), direction));
                }
                else
                {
                    this.Source.SortDescriptions.Insert(0, new SortDescription(currentHeader.Column.Header.ToString(), ListSortDirection.Ascending));
                }

                this.Source.Refresh();
            }

        }

//group////////////////////

private void btnGroup_Click(object sender, RoutedEventArgs e)
{
            this.Source.GroupDescriptions.Clear();

            PropertyInfo pinfo = typeof(object).GetProperty(cmbGroups.Text);
            if (pinfo != null)
                this.Source.GroupDescriptions.Add(new PropertyGroupDescription(pinfo.Name));

}

WPF代码如下

<ListView ItemsSource="{Binding}" x:Name="LvItems" ButtonBase.Click="ListView_Click" IsSynchronizedWithCurrentItem="True" Grid.Row="1" Margin="0,22,0,43">
        <ListView.GroupStyle>
            <GroupStyle>
                <GroupStyle.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock FontSize="15" FontWeight="Bold" Text="{Binding}"/>
                    </DataTemplate>
                </GroupStyle.HeaderTemplate>
            </GroupStyle>
        </ListView.GroupStyle>

    </ListView>

由于您使用的是 WPF,因此您应该使用 DataBindings。将 ICollectionView 作为属性公开并绑定在其上

public ICollectionView MyList
{
    get
    {
        if(_mylist == null)
            _mylist = CollectionViewSource.GetDefaultView(observableCollection);
        return _mylist;
    }
}

在 XAML 中,按如下方式应用绑定

<ListView ItemsSource="{Binding Path=MyList}"/>

现在您对该属性应用排序

MyList.SortDescriptions.Remove(...);
MyList.SortDescriptions.Add(...);

MyList.GroupDescription.Add(...);

这有一个缺点,即每个Remove or AddSortDescription 或 GroupDescription 将刷新 ListView。通常,如果您想在一个步骤中应用多次排序,则这是不需要的。然后您应该用以下内容将该块括起来:

using(MyList.DeferRefresh())
{
    //put your changes in sorting and grouping here
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WPF 中的 Icollectionview 排序和分组 的相关文章

随机推荐

  • 10k 租户和多租户数据库设计 [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我们正在尝试为新的 Web 应用程序决定数据库设计 我们预计将有近 10 000 个租户 并且希望将他们的数据保存在单独的数据库中 如
  • Qt iOS 运行失败

    当我尝试在 iOS 模拟器上运行我的应用程序时 应用程序输出 I see Starting remote process Run ended 当我尝试在 iPhone 上运行它时 Issues I see xcodebuild failed
  • 如何在休眠中为自身实体添加@onetoone映射

    如何为自身实体添加一对一映射 就像这个例子一样 我想为 Person 本身建立父子关系 Entity Table name PERSON public class Person Id Column name personId private
  • 在 make 中“触及”目标是什么意思?

    例如 从 mingw32 make exe help 选项 t touch Touch targets instead of remaking them 它只是意味着更新文件修改时间 这样下次就不会认为这些文件是旧的
  • CSS - 在电脑上分屏但在移动设备上堆叠

    我试图将我的页面分成 4 个相等的部分 我想将左上角水平分成 2 个部分 我主要关心的是它在移动设备上的表现 我不希望它像在电脑上那样被分割 我希望它被堆叠起来 块在另一个上面 如图所示 我想过引导网格 但我做不到 到目前为止我所拥有的内容
  • 如何使用量角器+角度获取迭代器索引/键?

    通过中继器查找元素时有没有办法访问迭代器索引 键 protractor By repeater id cat in pets 在本例中 我希望访问猫的 id id 不是表中显示为值的列之一 它用于导航ng click goto pets c
  • SSL_connect 返回=1 errno=0 状态=SSLv3 读取服务器证书 B:证书验证失败

    我在用Authlogic 连接 https github com viatropos authlogic connect用于第三方登录 运行适当的迁移后 Twitter Google yahoo 登录似乎工作正常 但 facebook 登录
  • 为什么 Python 中对集合的处理不统一?

    Python 中集合和列表的处理方式不同 并且似乎没有统一的方法来处理这两者 例如 将一个项目添加到set是使用完成的add方法 并且对于list它是使用完成的append方法 我知道这背后有不同的语义 但也有共同的语义 并且通常与某些集合
  • 用于电子邮件的 JUnit 报告单页 XSLT

    我有一个 Junit 进程 每天晚上运行大量数据完整性测试 我希望它以格式良好的 HTML 电子邮件形式发送结果 问题是 JUnit 中内置的 HTML 格式化程序使用框架和外部样式表 因此它不适合电子邮件 普通格式化程序将结果埋在一堆原本
  • 未捕获的语法错误:计算时出现意外的标识符

    我有一些返回一个的代码Uncaught SyntaxError当我运行它但我不明白为什么 我尝试将其通过 JSHint 但无济于事 这是明显错误的代码 function compute expr x string var whatisx x
  • Java8计算地图中对象列表的平均值

    初始数据 public class Stats int passesNumber int tacklesNumber public Stats int passesNumber int tacklesNumber this passesNu
  • MongoDB:如何在 C# 中加载带有嵌套数组的集合?

    我有一个名为 服务器 的集合 其中包含以下文档 name West ip 123 123 123 123 channels name English port 1234 status 0 name Spanish port 1235 sta
  • 为什么带有空格的 cookie 值到达客户端时会带有引号?

    我是一名 NET 开发人员 开始涉足 Java 在 NET 中 我可以将 cookie 的值设置为其中包含空格的字符串 new HttpCookie myCookieName my value 当我在客户端 JavaScript 读取该值时
  • 批处理文件重复以前的工作程序

    我需要有关批处理脚本的帮助 它运行得很好 但后来当我想运行它时 它不断重复我之前显示的结果 例如 我上周执行了一个名为运行 echo 程序上周首先运行 的程序 当我今天尝试通过 echo 这是今天 运行它时 它运行并显示之前的结果 PS 代
  • 从 Composer 在 dataproc 集群上执行 bash 脚本

    我想在使用简单的 shell 脚本创建集群后将 jar 添加到特定位置的 dataproc 集群中 创建 dataproc 集群后 我想自动执行此步骤以从 Composer 运行 下一步是执行 bash 脚本 该脚本会将 jar 添加到 d
  • jinja 2 库中的语法错误

    为了在 suse Linux 服务器上运行 IPython Notebook 我需要安装jinja2图书馆 pip 3 2 install jinja2 安装打印语法错误 https gist github com anonymous 62
  • TSLint 不适用于 CRA 和 TypeScript

    我花了几个小时绞尽脑汁试图为使用 create react app 创建的 TypeScript 项目启用 linting The wmonk create react app typescript https github com wmo
  • 从 vuex 存储访问 $vuetify 实例属性

    我正在使用vuetify并想改变主题vuex存储使用 vuetify https vuetifyjs com en style theme实例但我收到这个错误Cannot set property theme of undefined 这是
  • JDBCPreparedStatement - 使用相同的参数,可能吗?

    我正在使用 插入或更新 查询 如下所示 String sql INSERT INTO servlets path applicationId startTime numOfRequests totalResponseTime totalBy
  • WPF 中的 Icollectionview 排序和分组

    我在 WPF 中创建了一个 listview 控件并成功完全绑定Icollectionview的对象ObservableCollection 我的列表视图列是动态创建的 我必须对列表视图进行排序和分组 但它无法正常工作 我的代码如下 pri