0
votes

I have a problem with binding. I want to bind list items to the datagrid columns. One row in datagrid represents one list of items. Every item is in a column. For example, all items from lists with index 0 are in column with index 0.

My datagrid:

<DataGrid Name="AttacksForGroupsDG" 
              CanUserAddRows="False"
              CanUserDeleteRows="True"
              AutoGenerateColumns="False"
              DockPanel.Dock="Top"
              VerticalAlignment="Stretch"
              HorizontalAlignment="Stretch"
              Height="250">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Jméno vesnice" Binding="{Binding Name}" Width="120"/>
            <DataGridTextColumn Header="Souřadnice" Binding="{Binding Coords}" Width="70"/>
        </DataGrid.Columns>
    </DataGrid>

Next, I have a list of items to which I bind to. Every item of this list represents one row in my datagrid.

public abstract class Group<T>
    where T : Village
{
    public ObservableCollection<T> Villages { get; private set; }

    // the rest of the code I deleted for a clarity
}

Finally, I bind to this class. The properties Name and Coords I inherit from a class Village.

public sealed class Def : Village
{
    public List<int> Attacks { get; set; }

    public Def()
        : base()
    {
        Attacks = new List<int>();
    }
}

So, the first column in the datagrid will be with the Name property. The second column will be with the Coords property. The next columns I create dynamically in code according to the number of items in the list Attacks in the class Def.

I don't know how to bind items from that list to individual columns.

I appreciate any advice.

1
first 2 cols are fixed and then there can be unlimited columns ? - AnjumSKhan
@AnjumSKhan Exactly. I create the first two columns in XAML and other columns I create in code depending on a size of the list. - Ladislav Ondris
search google for : wpf datagrid variable number of columns - AnjumSKhan
Thank you. It hadn't occurred to me. Helped me this tutorial: elegantcode.com/2010/03/08/… - Ladislav Ondris

1 Answers

0
votes

Add the ItemSource attribute to your DataGrid tag with a binding on your Villages list:

     <DataGrid Name="AttacksForGroupsDG" 
          CanUserAddRows="False"
          CanUserDeleteRows="True"
          AutoGenerateColumns="False"
          DockPanel.Dock="Top"
          VerticalAlignment="Stretch"
          HorizontalAlignment="Stretch"
          Height="250"
          ItemsSource="{Binding Villages}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Jméno vesnice" Binding="{Binding Name}" Width="120"/>
            <DataGridTextColumn Header="Souřadnice" Binding="{Binding Coords}" Width="70"/>
        </DataGrid.Columns>
    </DataGrid>