Gerard
Gerard

Reputation: 13417

Why an exception when I add a DataGridCell style?

The following xaml gives the exception: "Items collection must be empty before using ItemsSource."
In code behind we have simply:

public MainWindow()
{
    InitializeComponent();

    DataContext = Customers;

    Customers.Add(new Customer { Voornaam = "Tom", Achternaam = "Jones" });
    Customers.Add(new Customer { Voornaam = "Joe", Achternaam = "Thompson" });
    Customers.Add(new Customer { Voornaam = "Jill", Achternaam = "Smith" });
}

private List<Customer> _customers = new List<Customer>();
public List<Customer> Customers { get { return _customers; }}

<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="True">
   <Style TargetType="{x:Type DataGridCell}" />
</DataGrid>

Without the Style there is no exception.
The fact that the Style is empty is just because I was looking for the minimal code that gives the exception. Adding a setter doesn't change anything.
The reaseon for the usage of the style is that I want to tweak the controltemplate for the autogenerated columns.

Upvotes: 0

Views: 54

Answers (1)

Justin XL
Justin XL

Reputation: 39006

Your style is fine. The issue is how you apply the style to your DataGrid.

The way you define the style is like trying to say "let's inject the style to the Content of the DataGrid", and that's exactly why you see this error.

Items collection must be empty before using ItemsSource.

Try using the following code to add the style to the DataGrid's CellStyle property instead.

<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="True">
    <DataGrid.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
        </Style>        
    </DataGrid.CellStyle>
</DataGrid>

Upvotes: 3

Related Questions