【问题标题】:Get row index during loop through all DataGrid ItemSource在循环遍历所有 DataGrid ItemSsource 期间获取行索引
【发布时间】:2019-01-25 02:18:58
【问题描述】:

我想获取特定 DataGrid 项目的行索引或项目索引。我已经通过 itemsource 从循环中获取所有项目,

foreach (Item item in Datagrid.ItemsSource)
                {
                    if (item.Code != null)
                    {
                        if (code == item.Code)
                        {
                            MessageBox.Show("equal");
                        }
                    }
                }

在上面的代码中,如果code==item.code 然后出现消息,我已经应用了一些条件。在这种情况下,我也想获得该项目索引或行索引。如何获得。

注意:我有一个想法在 Datagrid itemsource 加载时执行此操作,还将 Datagrid 的索引与 Item 对象绑定并在需要时获取。但这似乎是复杂的逻辑。有没有最简单的解决方案?

数据网格:

<DataGridTextColumn Header="Code" Width="1*" Binding="{Binding Code, Mode=TwoWay}"/>

通过这个加载Datagrid项,

void AddValues()
    {
        Datagrid.ItemsSource = null;
        List<Item> list = new List<Item>();
        list.Clear();

        for(int i = 0; i<30; i++)
        {
            string number = i.ToString();
            Item item = new Item()
            {
                Code = "1",
            };
            list.Add(item);
        }
        Datagrid.ItemsSource = list;
    }

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    让 LINQ 统计不匹配的行数,相当于第一个匹配项的从零开始的索引。

    var index = Datagrid.ItemsSource.Cast<Item>()
        .TakeWhile
        ( 
            item => item.Code != code 
        )
        .Count();
    

    为了代码清晰,您可能希望将其放在扩展方法中:

    public static class ExtensionMethods
    {
        static public int IndexOf<T>(this IEnumerable<T> source, Func<T,bool> func)
        {
            return source.TakeWhile( item => !func(item) ).Count();
        }
    {
    
    var index = DataGrid.ItemsSource.Cast<Item>().IndexOf( i => i.Code == code );
    

    【讨论】:

    • 如果 DataGrid 通过单击列的标题按某列排序,我希望此方法返回错误的索引
    猜你喜欢
    • 2012-06-17
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多