2010-11-19 98 views
0

有人能告訴我爲什麼沒有數據在我的WPF的DataGrid被displaysed用下面的代碼:WPF Datagrid的:無數據顯示被

<Window x:Class="WpfApplication1.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="300" Width="300" 
    xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" 
     > 
    <Grid> 
     <my:DataGrid Name="myDataGrid" ItemsSource="{Binding Customers}"> 
      <my:DataGrid.Columns> 
       <my:DataGridTextColumn Header="Name" Binding="{Binding Name}" /> 
       <my:DataGridTextColumn Header="Name1" Binding="{Binding Name1}" /> 
      </my:DataGrid.Columns> 
     </my:DataGrid> 
    </Grid> 
</Window> 

public partial class Window1 : Window 
{ 
    public Window1() 
    { 
     InitializeComponent(); 

     IList<Customers> list = new List<Customers>(); 
     list.Add(new Customers() { Name = "Name1", Name2 = "Name2" }); 
     list.Add(new Customers() { Name = "Name1", Name2 = "Name2" }); 
     list.Add(new Customers() { Name = "Name1", Name2 = "Name2" }); 

     myDataGrid.DataContext = new Customers() { Name = "Name1", Name2 = "Name2" }; 
    } 
} 

public class Customers 
{ 
    public string Name { get; set; } 
    public string Name2 { get; set; } 
} 

回答

1

嘛。這裏有很多問題。

  1. 要設置DataContextnew Customers()對象,而不是客戶的集合(即list
  2. 應該是爲了直接綁定的ItemsSource到將是集合DataContext的ItemsSource="{Binding}"
  3. 據我記得DataGrid它的AutoGenerateColumns默認是true,所以它會有4列,2自己創建和2自動生成。
+0

Ups,在我的代碼中,我確實將DataContext設置爲我的List。您在上面提出的第2點解決了問題,謝謝 – Bob 2010-11-19 09:24:11

0

除了一切的α-老鼠說,這是所有的錢...

考慮對你的數據上下文類型的ObservableCollection的類成員:

public partial class Window1 : Window 
{ 
    private ObservableCollection<Customers> customers; 

    public Window1() 
    { 
     InitializeComponent(); 

     this.customers = new ObservableCollection<Customers>(); 

使用一個ObservableCollection而不是List確保對網格自動更改集合內容,而無需執行任何類型的NotifyPropertyChanged。

+0

當然,您應該真正將View的DataContext設置爲ViewModel類,並使您的Customers集合成爲ViewModel的一個屬性。 – Steve 2010-11-19 09:49:47