0

I'm having a Collection of type 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" },
}

The appropriate 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>

I need to set the Index value in Column 1. Kindly assist me how to set the index value for the column which is associated with the collection.

Note: I need this in XAML Level not in C# Code Level Implementation

Required Data Grid : Model Snapshot

enter image description here

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109

1 Answers1

2

You don't need a custom column for this purpose just add LoadingRow event to your DataGrid and remove <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>

Then:

private void Grid1_OnLoadingRow(object sender, DataGridRowEventArgs e)
{
    e.Row.Header = (e.Row.GetIndex()).ToString();
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • can you please add the Full XAML Code please. –  Jun 23 '16 at 06:38
  • @IRPunch See my updated answer. – Salah Akbari Jun 23 '16 at 06:39
  • Thanks a lot. Can you please explain me. how to access the row number in datatrigger ? For example I need to change the color of the text if the row number is 2. How could I identify the property ? –  Jun 23 '16 at 06:54