2014-01-15 66 views
0

我是新來的wpf和MVVM,在我的Gridview中有不同的列,不同的行。 我想編號每一行。我如何在GridView中添加SI編號在wpf中mvvm

SI No.  Name Age 

    1   abc 12 
    2   edf 15 
    3   fsd 25 

使用WPF MVVM我如何設置這個SI號順序 - 但現場SI.No不能添加到數據庫中,並且當行刪除,這將是正確的順序...

+0

您可以使用'RowHeader'的..的 – Sankarann

+0

可能重複[在GridView中獲取索引](http://stackoverflow.com/questions/9678386/getting-indexes-in-gridview) – Sheridan

+0

如何綁定到gridview? – Jinesh

回答

0

我會做這樣的:

首先創建這樣一個類:

public class DataWithRowNumber 
{ 
    public int Index { get; private set; } 
    public string Name { get; private set; } 
    public int Age { get; private set; } 

    public DataWithRowNumber(int index, string name, int age) 
    { 
     Index = index; 
     Name = name; 
     Age = age; 
    } 
} 

這裏只是爲你的視圖模型的一些示例代碼:

public List<DataWithRowNumber> Data 
{ 
    get 
    { 
     // just to simulate some data from db 
     DataTable table = new DataTable(); 
     table.Columns.Add("Name", typeof(string)); 
     table.Columns.Add("Age", typeof(int)); 

     table.Rows.Add(new object[] {"abc", 12}); 
     table.Rows.Add(new object[] {"edf", 15}); 
     table.Rows.Add(new object[] {"fsd", 25}); 

     // code for conversion to appropriate list 
     List<DataWithRowNumber> list = new List<DataWithRowNumber>(); 
     int index = 1; 
     foreach (DataRow row in table.Rows) 
     { 
      object[] items = row.ItemArray; 
      list.Add(new DataWithRowNumber(index, (string)items[0], (int)items[1])); 
      index++; 
     } 

     return list; 
    } 
} 

而且在你看來,你有這樣的事情:

<ListView ItemsSource="{Binding Path=Data}"> 
    <ListView.View> 
     <GridView> 
      <GridViewColumn DisplayMemberBinding="{Binding Path=Index}" Header="SI No." /> 
      <GridViewColumn DisplayMemberBinding="{Binding Path=Name}" Header="Name" /> 
      <GridViewColumn DisplayMemberBinding="{Binding Path=Age}" Header="Age" /> 
     </GridView> 
    </ListView.View> 
</ListView>