我在WPF中設置了LINQ-to-SQL/NorthWind。爲什麼我可以綁定到ListBox但不能綁定到WPF中的DataGrid?
ListBox顯示數據,但DataGrid沒有(沒有錯誤,只是不顯示任何東西)。
我引用了WPFToolkit.dll。
爲什麼DataGrid沒有顯示ListBox可以顯示的數據?
XAML:
<Window x:Class="TestLinq343.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<DataTemplate x:Key="ShowCustomer">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding CategoryID}"/>
<TextBlock Text=": "/>
<TextBlock Text="{Binding ProductName}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<dg:DataGrid x:Name="TheDataGrid" AutoGenerateColumns="True"></dg:DataGrid>
<ListBox x:Name="TheListBox" ItemTemplate="{StaticResource ShowCustomer}"/>
</Grid>
</Window>
後面的代碼:
using System.Linq;
using System.Windows;
using TestLinq343.Model;
using Microsoft.Windows.Controls;
namespace TestLinq343
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
NorthwindDataContext db = new NorthwindDataContext();
var sortedProducts =
from p in db.Products
orderby p.UnitsInStock descending
select p;
TheDataGrid.ItemsSource = sortedProducts;
TheListBox.ItemsSource = sortedProducts;
}
}
}
試過了,還是空白,是的AutoGenerateColumns true時默認情況下,我在下面演練http://windowsclient.net/wpf/ wpf35/wpf-35sp1-toolkit-datagrid-feature-walkthrough.aspx,它定義了XAML中的ItemsSource,但應該不重要,應該如何? – 2009-02-26 14:46:07