我有一个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(); } }
解决方法
您正试图将列直接放入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>