Setting Column Numbers of Data Grid with WPF Binding

I have a DataGrid that one of its columns needs to get the serial number of the row in the Grid, the DataGrid is bound to the following list:

public IList<xx> ListXX= new List<xx>();

      

The xx class contains several variables that bind to the rest of the columns.

How do I link the column number in the list to my column in the DataGrid?

+3


source to share


3 answers


I solved the problem this way:

I created a converter for the index:

public class IndexConverter : IMultiValueConverter
{
    public object Convert(
        object[] values, Type targetType,
        object parameter, System.Globalization.CultureInfo culture)
    {
        var xx= values[0] as xx;
        var listxx= values[1] as List<xx>;
        if (xx== null)
            return null;
        return (listxx.FindIndex(x => x == xx) + 1).ToString();
    }

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

      



In the DataGrid, I bind the column to a MultiBinding:

 <DataGridTextColumn Header="#" IsReadOnly="True">
     <DataGridTextColumn.Binding>
           <MultiBinding Converter="{StaticResource indexConverter}">
                <Binding />
                 <Binding RelativeSource=
                     "{RelativeSource AncestorType={x:Type DataGrid}}"
                     Path="ItemsSource"></Binding>
            </MultiBinding>
     </DataGridTextColumn.Binding>
  </DataGridTextColumn>

      

+2


source


With limited information that you have provided. I am assuming you are trying to bind this list to your WPF grid. You can use this as shown below.

this.dataGrid1.ItemsSource = list;

      



One more thing is to make sure your XAML AutoGenerateColumn is set to true.

if it doesn't work. Post more information like what your XML looks like and how you are trying to link it in code.

+1


source


if you know your order ListXX

than you can do something like:

        <DataGrid>
            <DataGridTextColumn Header="#" IsReadOnly="True" Binding="{Binding LisXX[0]}"></DataGridTextColumn>
            <DataGridTextColumn Header="#" IsReadOnly="True" Binding="{Binding LisXX[5]}"></DataGridTextColumn>
            <DataGridTextColumn Header="#" IsReadOnly="True" Binding="{Binding LisXX[1]}"></DataGridTextColumn>
        </DataGrid>

      

+1


source







All Articles