Search code examples
c#wpfdata-bindingdatagriditemsource

Issue when dynamically binding to a datagrid


OK I have a weird little issue I hope someone can help me with.

To set the scene, I first of all have an object:

public class Date
{
    public DateTime _WeekDate;
    public ICollectionView _WeekData;
}

I have a combobox which displays a list of the Date objects.

<ComboBox Name="cbPickupDate" ItemsSource="{Binding Path=PickupDates}" DisplayMemberPath="WeekDate" />

OK, now I take the selected date object's collection to provide an itemssource for my datagrid:

<my:DataGrid ItemsSource="{Binding ElementName=cbPickupDate, Path=SelectedItem.WeekData}">
    <my:DataGrid.Columns>
        <my:DataGridTextColumn Binding="{Binding Path=ReqID}" Header="Request ID" />
        <my:DataGridTextColumn Binding="{Binding Path=LineID}" Header="Line ID" />
        <my:DataGridTextColumn Binding="{Binding Path=OrderID}" Header="Order ID" />
    </my:DataGrid.Columns>
</my:DataGrid>

This all works very nicely, as I choose different options from the combobox the datagrid changes it's itemssource.

However, the datagrid adds an extra column for each value within my WeekData item on top of the ones I have specified. So using the example I've shown it would display 3 columns of reqID, lineID and OrderID and 3 more columns of exactly the same thing, so 6 in total.

Any help is appreciated, I'm really scratching my head over this one.

Thanks in advance, SumGuy.


Solution

  • Turn off AutoGenerateColumns

    <my:DataGrid ItemsSource="{Binding ElementName=cbPickupDate, Path=SelectedItem.WeekData}"
                 AutoGenerateColumns="False">
        <my:DataGrid.Columns>
            <my:DataGridTextColumn Binding="{Binding Path=ReqID}" Header="Request ID" />
            <my:DataGridTextColumn Binding="{Binding Path=LineID}" Header="Line ID" />
            <my:DataGridTextColumn Binding="{Binding Path=OrderID}" Header="Order ID" />
        </my:DataGrid.Columns>
    </my:DataGrid>