【问题标题】:Add the Index Number of a ViewModel's members as Row Number in DataGrid将 ViewModel 成员的索引号添加为 DataGrid 中的行号
【发布时间】:2014-01-07 09:09:18
【问题描述】:

目前,我正在使用以下代码调用我的转换器,它为我做这件事,输入我需要的行号。

<DataGridTextColumn Header="NO" Width="22" IsReadOnly="True" x:Name="rowNumber">
                    <DataGridTextColumn.HeaderStyle>
                        <Style TargetType="{x:Type DataGridColumnHeader}">
                            <Setter Property="FontSize" Value="10" />
                            <Setter Property="Margin" Value="0"/>
                        </Style>
                    </DataGridTextColumn.HeaderStyle>
                    <DataGridTextColumn.Binding>
                        <MultiBinding Converter="{StaticResource rowNumberConverter}">
                            <Binding />
                            <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}" />
                        </MultiBinding>
                    </DataGridTextColumn.Binding>
                </DataGridTextColumn>

还有转换器:

class RowNumberConverter : IMultiValueConverter
    {
        #region IMultiValueConverter Members

        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {

            //get the grid and the item
            Object item = values[0];
            DataGrid grid = values[1] as DataGrid;

            int index = grid.Items.IndexOf(item) + 1 ;

            return index.ToString().PadLeft(2, '0');
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

但是,这在我们的新要求(分页)中会失败。这个转换器当然不会继续计数,因为它只引用 DataGrid 中的行。

谁能告诉我如何在下一页继续计算行数? 坚持干净的 MVVM 模式是必要的。

感谢您的帮助。

【问题讨论】:

  • 天啊,这太可怕了,绝对不是 MVVM!您不应该在这样的转换器中访问 UI 元素。尝试绑定到DataGrid.ItemsSourceDataGrid.Items 属性而不是整个DataGrid
  • 看看这里:[如何在 ListView 中显示行号?][1] [1]:stackoverflow.com/questions/660528/…

标签: c# wpf mvvm datagrid rowcount


【解决方案1】:

我认为视图模型只是提供所有要显示的数据的元素。如果需要显示项目编号,则只需向正在显示的元素添加另一个属性。

通过这种方式,您可以使用所需的任何值填充数字,无论数字是否在一个连续序列中,或者您是否有更复杂的编号系统。

【讨论】:

  • 确实有道理,而且我可以避免您在上面指出的丑陋。我试图找出是否有一种方法可以动态添加这些数字。
  • 有...只需在视图模型中循环遍历您的集合并每次设置相关数字。
  • 是的,我就是这么做的。我想看看是否有办法只修补视图。再次感谢您的帮助,一如既往。
猜你喜欢
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 2021-06-25
  • 1970-01-01
  • 2021-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多