如何在wpf mvvm中的Gridview中添加SI号

时间:2014-01-15 08:59:32

标签: wpf mvvm

我是wpf和MVVM的新手,在我的Gridview中有不同的列,不同的行。 我想对每一行进行编号。

   SI No.     Name    Age

    1         abc    12
    2         edf    15
    3         fsd    25

我如何使用wpf mvvm按此顺序设置此SI号?但是字段SI.No无法添加到数据库中,当一行删除时它将按正确的顺序...

1 个答案:

答案 0 :(得分: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;
    }
}

以下是viewmodel的一些示例代码:

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>