2015-02-09 89 views
0

我有DataGrid其中ItemsSource绑定到ViewModel中的ObservableCollection<LogEntry>。在DataGrid中显示LogEntry-classes的属性MessageDate在DataGrid中显示行号

ItemsSource中的项目更改频率取决于外部选择。

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

有没有一种简单的方法可以在WPF中用MVVM做到这一点,还是必须创建一个新类(例如RowLogEntry),它继承自LogEntry并为行号提供属性?

+0

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

使用您使用的MVVM? – 2015-02-09 09:24:14

+0

是的,我正在使用MVVM – Tomtom 2015-02-09 09:26:21

+0

请参阅下面的答案。 – 2015-02-09 09:30:20

回答

1

一种方法是将它们添加在LoadingRow事件为DataGrid

<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:此,而是如果你想从1只

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

希望这有助于