0

My DataGrid looks like this

enter image description here

Implementation I took exactly from here

https://stackoverflow.com/a/15061668/5709159

so, I have the save converter

public class RowToIndexConverter : MarkupExtension, IValueConverter
{
    static RowToIndexConverter converter;

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        DataGridRow row = value as DataGridRow;
        if (row != null)
            return row.GetIndex();
        else
            return -1;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (converter == null) converter = new RowToIndexConverter();
        return converter;
    }

    public RowToIndexConverter()
    {
    }
}

But what issue is when I am deleting for example rows 2, 3, 4, so order number of rows are not updating. And I get such result

enter image description here

So, question is - how to update row order number after that row was deleted?

coder_g
  • 41
  • 9
Sirop4ik
  • 4,543
  • 2
  • 54
  • 121

1 Answers1

3

So, eventually I found solution here

https://ru.stackoverflow.com/a/853244/195957

Firstly you need to create such class

public class NumerRow : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        DataGridRow row = values[0] as DataGridRow;
        if (row.DataContext?.GetType().FullName == "MS.Internal.NamedObject") return null;
        return (row.GetIndex() + 1).ToString();
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        => throw new NotSupportedException();
}

And in .xalm

<DataGridTextColumn Header="№">
    <DataGridTextColumn.Binding>
        <MultiBinding Converter="{StaticResource NumerRow}">
            <Binding Mode="OneWay" RelativeSource="{RelativeSource AncestorType={x:Type DataGridRow}}"/>
            <Binding Mode="OneWay" RelativeSource="{RelativeSource AncestorType={x:Type DataGrid}}" Path="Items.Count"/>
        </MultiBinding>
    </DataGridTextColumn.Binding>
</DataGridTextColumn>

Result is

введите сюда описание изображения

Sirop4ik
  • 4,543
  • 2
  • 54
  • 121