【问题标题】:Row number in wpf datagrid rowwpf datagrid行中的行号
【发布时间】:2014-03-27 04:52:42
【问题描述】:

我有 datagrid 绑定了一个 ICollectionView 列表对象。基本上,这些行是根据一列中的值过滤的。现在每一行都有一个索引列。这基本上是行号。由于行已被过滤,因此行号会发生变化。如何处理?

基本上 DataGrid 绑定到一个类对象列表。

 Class city
 {
   Int Index;
   String Name;
   string location; 
  }

 List<city> Cities;

当我创建对象时,索引的值取决于索引中的项目数。所以第一个对象的索引=0,第二个对象的索引=1,依此类推。索引是网格中的一列。现在假设我有 2 个位于迪拜的对象。和一个开罗(第三个对象,索引= 3)。当我选择开罗时,只会显示该行。但是由于我之前添加了索引,因此索引号=3,因为我希望它为 1,因为过滤器之后只有一行。

【问题讨论】:

  • 请发布一些代码以方便我们帮助您。听起来您正在重建索引 AFTER 应用过滤器,这是导致问题的原因吗?
  • 添加了更多描述请检查。
  • 你打算用这个Index 属性做什么。它是业务逻辑的一部分,还是您创建它是为了在视图中显示?如果仅用于显示,请查看实现 AlternationIndex
  • @Bharathram Attiyannan 它的唯一或显示目的.. 你能给我示例代码吗.. 我没有明白 AlternateIndex 的意思

标签: c# .net wpf xaml data-binding


【解决方案1】:

通常需要做的是首先设置索引的值,然后应用过滤器。

包括 System.Linq 命名空间并添加以下内容

cities = cities.Select((item, index) =>
        new city()
        {
            Index = index,
            Name = item.Name,
            location =  item.location
        });

这将返回第一个索引为零的城市列表。如果您希望它从一个开始,只需将其更改为:

cities = cities.Select((item, index) =>
        new city()
        {
            Index = index + 1,
            Name = item.Name,
            location =  item.location
        });

完成此操作后,您应该应用您的过滤器,除非您更改值,否则不应覆盖它。

【讨论】:

    【解决方案2】:

    当你想显示行索引时,你可以使用AlternationIndex。使用AlternationIndex 时有两点很重要:

    • 为控件设置AlternationCount。这就像 AlternationIndex 的计数限制,如果您的元素数量超过该计数,它将从 0 重新开始。理想情况下,如果您不希望它从 0 重新启动,您可以将其绑定到 Count Of Items
    • 绑定 AlternationIndex 时请注意源。对于 ListBox,它将是 {RelativeSource AncestorType=ListBoxItem} 对于其他人,它可以是 {RelativeSource Mode=TemplatedParent}

    试试下面这个示例:

    <ListBox Name="CityListBox" AlterationCount={Binding CountOfItems}
        <ListBox.ItemTemplate>
            <DataTemplate DataType="City">
                <TextBlock>
                        <Run Text="{Binding Name}"></Run>
                        <Run Text=" : "></Run>
                        <Run Text="{Binding Country}"></Run>
                        <Run Text=" : "></Run>
                        <Run Text="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem},
                                    Path=(ItemsControl.AlternationIndex), Mode=OneWay}"></Run>
                </TextBlock>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    输出

    CityA : CountryA : 0
    CityB : CountryB : 1
    CityC : CountryC : 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      • 2011-07-29
      • 2016-08-21
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      相关资源
      最近更新 更多