在 DataGrid 中显示行号
Show row-number in DataGrid
我有一个 DataGrid
,其中 ItemsSource
绑定到 ViewModel 中的 ObservableCollection<LogEntry>
。在 DataGrid
中,显示 LogEntry
-class 中的属性 Message
和 Date
。
此 ItemsSource
中的项目根据外部选择经常变化。
现在我想在 DataGrid
中添加一个显示行号的列。
在 WPF 中使用 MVVM 是否有一种简单的方法可以做到这一点,或者我是否必须创建一个新的 class(例如 RowLogEntry
)继承自 LogEntry
并提供 属性 对于行号?
一种方法是将它们添加到 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();
}
希望对您有所帮助
我有一个 DataGrid
,其中 ItemsSource
绑定到 ViewModel 中的 ObservableCollection<LogEntry>
。在 DataGrid
中,显示 LogEntry
-class 中的属性 Message
和 Date
。
此 ItemsSource
中的项目根据外部选择经常变化。
现在我想在 DataGrid
中添加一个显示行号的列。
在 WPF 中使用 MVVM 是否有一种简单的方法可以做到这一点,或者我是否必须创建一个新的 class(例如 RowLogEntry
)继承自 LogEntry
并提供 属性 对于行号?
一种方法是将它们添加到 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();
}
希望对您有所帮助