【问题标题】:Show row-number in DataGrid在 DataGrid 中显示行号
【发布时间】:2015-02-09 09:20:30
【问题描述】:

我有一个DataGrid,其中ItemsSource 绑定到ViewModel 中的ObservableCollection<LogEntry>。在DataGrid 中显示来自LogEntry 类的属性MessageDate

ItemsSource 中的项目经常根据外部选择而变化。

现在我想在我的DataGrid 中添加一个显示行号的附加列。

有没有一种简单的方法可以在带有 MVVM 的 WPF 中执行此操作,还是我必须创建一个继承自 LogEntry 并提供行号属性的新类(例如 RowLogEntry)?

【问题讨论】:

  • 你在使用 MVVM 吗?
  • 请看下面我的回答。

标签: c# wpf mvvm datagrid


【解决方案1】:

一种方法是将它们添加到 DataGrid 的 LoadingRow 事件中

 <DataGrid Name="DataGrid" LoadingRow="DataGrid_LoadingRow" ...

    void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        e.Row.Header = (e.Row.GetIndex()).ToString(); 
    }

当从源列表中添加或删除项目时,数字可能会在一段时间内不同步

在源列表中添加或删除项目时,数字可能会在一段时间内不同步。For a fix to this, see the attached behavior here:

<DataGrid ItemsSource="{Binding ...}"
          behaviors:DataGridBehavior.DisplayRowNumber="True">

如果您想从 1 开始计数,请改用它

void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
    e.Row.Header = (e.Row.GetIndex()+1).ToString(); 
}

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2016-08-30
    • 2013-02-10
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 2010-10-11
    相关资源
    最近更新 更多