在DataGrid中设置增量编号或索引值

时间:2016-06-23 06:30:56

标签: c# wpf xaml datagrid

我的收藏类型为 Mobile

public class Mobile
{
    public string MobileName { get; set; }
    public string MobileOS { get; set; }
}

ObservableCollection<Mobile> MobileList = new ObservableCollection<Mobile>()
{
    new Mobile() { MobileName = "iPhone 6", MobileOS = "IOS" },
    new Mobile() { MobileName = "Galaxy S6", MobileOS = "Android" },
    new Mobile() { MobileName = "Lumina", MobileOS = "Windows" },
}

适当的WPF DataGrid(XAML)

<DataGrid Name="Grid1" AutoGenerateColumns="False" ItemsSource="{Binding MobileList, UpdateSourceTrigger=PropertyChanged}">
    <DataGrid.Columns>
        <!--Column 1-->
        <DataGridTextColumn Binding="" Header="Index" />
        <!--Column 2-->
        <DataGridTextColumn Binding="{Binding MobileName}" Header="Name" />
        <!--Column 3-->
        <DataGridTextColumn Binding="{Binding MobileOS}" Header="OS" />
    </DataGrid.Columns>
</DataGrid>

我需要在第1列中设置索引值。请帮助我如何设置与集合相关联的列的索引值。

  

注意:我需要在XAML级别而非C#代码级别实现中

必需的数据网格:模型快照

enter image description here

1 个答案:

答案 0 :(得分:1)

为此,您不需要自定义列,只需将LoadingRow事件添加到DataGrid并删除<DataGridTextColumn Header="Index" />

<DataGrid Name="Grid1" AutoGenerateColumns="False" LoadingRow="Grid1_OnLoadingRow">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding MobileName}" Header="Name" />
        <DataGridTextColumn Binding="{Binding MobileOS}" Header="OS" />
    </DataGrid.Columns>
</DataGrid>

然后:

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