0

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.

4

1 回答 1

3

你的风格很好。问题是如何将样式应用到DataGrid.

您定义样式的方式就像试图说“让我们将样式注入到ContentDataGrid中,这正是您看到此错误的原因。

在使用 ItemsSource 之前,项目集合必须为空。

尝试使用以下代码将样式添加到DataGrid'CellStyle属性。

<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="True">
    <DataGrid.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
        </Style>        
    </DataGrid.CellStyle>
</DataGrid>
于 2014-12-17T00:22:29.547 回答