How to show row-number in first column of WPF Datagrid

前端 未结 2 1261
一向
一向 2020-11-30 09:06

While searching I found that, row number can be set to RowHeader easily:

void datagrid_LoadingRow(object sender, DataGridRowEventArgs e) 
{ 
     e.Row.Heade         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 10:08

    I used Andys example, but I needed to use it from the code behind, so he is my code just in case anyone is looking to do the same as googling was a bit barren.

    The C#

        DataGrid dataGrid = new DataGrid();
    
        DataGridTextColumn column0 = new DataGridTextColumn();
        column0.Header = "#";
    
        Binding bindingColumn0 = new Binding();
        bindingColumn0.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(DataGridRow), 1);
        bindingColumn0.Converter = new RowToIndexConvertor();
    
        column0.Binding = bindingColumn0;
    
        dataGrid.Columns.Add(column0);
    

    Andy's Converter, just added return row.GetIndex() - 1; to start the count at 1, rather than 0.

    public class RowToIndexConvertor : MarkupExtension, IValueConverter
    {
        static RowToIndexConvertor convertor;
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            DataGridRow row = value as DataGridRow;
    
            if (row != null)
            {
                return row.GetIndex() + 1;
            }
            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 (convertor == null)
            {
                convertor = new RowToIndexConvertor();
            }
    
            return convertor;
        }
    
    
        public RowToIndexConvertor()
        {
    
        }
    }
    

    Also don't forget the using's

    using System;
    using System.Windows.Data;
    using System.Windows.Controls;
    using System.Windows.Markup;
    

提交回复
热议问题