Jakobinec
Jakobinec

Reputation: 63

Avalonia DataGrid add row number by using styles

I have many DataGrid elements in my solution and I need to add row numbers there. In Avalonia Github page they advices to use style. enter image description here

Could you tell me please how to create such style and show rowNumbers in first DataGrid column.

Upvotes: 0

Views: 466

Answers (1)

alvahtin
alvahtin

Reputation: 3

Style, example:

<DataGrid>
     <DataGrid.Styles>
        <Style Selector="DataGridRow">
              <Setter Property="Header" Value="{Binding Converter={StaticResource NumerRow}, Mode=OneWay, RelativeSource={RelativeSource Self}}" />
        </Style>
    </DataGrid.Styles>
    <DataGrid.Columns>
            .........
    </DataGrid.Columns>
</DataGrid>

Converter:

public class NumerRow : IValueConverter
{
    public object Convert(object? value, Type TargetType, object? parameter, CultureInfo culture)
    {
        try
        {
            if (value is DataGridRow row)
            {
                return (row.GetIndex() + 1).ToString();
            }
            else
            {
                return "*";
            }
        }
        catch
        {
            return "*";
        }
    }

    public object ConvertBack(object? value, Type TargetType, object? parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

But this numer set when create row and don't chage. When you delete row, or insert, numer of rows, which lower, don't changed.

Upvotes: 0

Related Questions