我有一个AutoGenerateColumns
WPF-DataGrid绑定到LINQ-to-SQL的代码隐藏,工作正常。
但是当我取消AutoGenerateColumns
并定义我自己的列时,它告诉我“在使用ItemsSource之前,items集合必须为空。”
但是我没有绑定我的XAML中的ItemSource
所以我不明白为什么它不是空的。 我需要更改哪些内容才能定义自己的列?
XAML:
<UserControl x:Class="TestDataGrid566.AppPages.ManageCustomers"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
Loaded="UserControl_Loaded">
<toolkit:DataGrid x:Name="TheDataGrid"
CanUserAddRows="False"
AlternatingRowBackground="#ddd"
CanUserSortColumns="true"
PreviewKeyDown="TheDataGrid_PreviewKeyDown"
AutoGenerateColumns="False"
RowEditEnding="TheDataGrid_RowEditEnding">
<toolkit:DataGridTextColumn Header="Contact Name" Width="SizeToCells"
Binding="{Binding ContactName}"
IsReadOnly="False"/>
</toolkit:DataGrid>
</UserControl>
代码隐藏:
public partial class ManageCustomers : UserControl
{
private NorthwindDataContext _db = new NorthwindDataContext();
public ManageCustomers()
{
InitializeComponent();
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
LoadData();
}
public void LoadData()
{
var customers = from c in _db.Customers
select c;
TheDataGrid.ItemsSource = customers.ToList();
}
}
答案 0 :(得分:22)
您正在尝试将列直接放入DataGrid
(因此它会尝试将列放在网格的Items
集合中,这可以解释您的错误)。您需要将其放在Columns
集合中:
<toolkit:DataGrid x:Name="TheDataGrid"
CanUserAddRows="False"
AlternatingRowBackground="#ddd"
CanUserSortColumns="true"
PreviewKeyDown="TheDataGrid_PreviewKeyDown"
AutoGenerateColumns="False"
RowEditEnding="TheDataGrid_RowEditEnding">
<toolkit:DataGrid.Columns>
<toolkit:DataGridTextColumn Header="Contact Name" Width="SizeToCells"
Binding="{Binding ContactName}"
IsReadOnly="False"/>
</toolkit:DataGrid.Columns>
</toolkit:DataGrid>