2013-03-18 113 views
2

我知道我張貼了這個問題,但已接受我的最後一個問題的答案,並通過我意識到這不是我一直在尋找答案的文章如下。我再次發佈了一些示例代碼。WPF8/C# - 將數據綁定到網格

我想從一個集合填充網格(不是一個DataGrid)使用數據。這是我的,但它不起作用。如果我刪除集合並將DataContext設置爲單個對象,但不能作爲集合。

XAML

Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> 
     <StackPanel> 
      <TextBlock Text="{Binding Path=StudentName}" /> 
     </StackPanel> 
</Grid> 

MainPage.xaml.cs中

public MainPage() 
    { 
     InitializeComponent(); 

     ObservableCollection<Student> ob = new ObservableCollection<Student>(); 

     ob.Add(new Student() 
     { 
      StudentName = "James Jeffery" 
     }); 

     ob.Add(new Student() 
     { 
      StudentName = "Sian Ellis" 
     }); 



     this.DataContext = ob; 

     // Sample code to localize the ApplicationBar 
     //BuildLocalizedApplicationBar(); 
    } 

這已被竊聽我小時。我似乎無法用集合填充網格。 Google上的每個示例都顯示了ListView等。我想填充一個Grid,並且只填充一個Grid。

有關如何實現此目的的任何建議?

+0

看起來您沒有爲Grid的ItemsSource設置數據上下文。 – Reddog 2013-03-19 00:06:27

回答

1

作爲另一個答覆中提到,您需要一個ItemsControl:背後

<Window x:Class="MiscSamples.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <ItemsControl ItemsSource="{Binding}"> 
     <ItemsControl.ItemsPanel> 
      <ItemsPanelTemplate> 
       <UniformGrid IsItemsHost="True" Rows="3" Columns="3"/> 
      </ItemsPanelTemplate> 
     </ItemsControl.ItemsPanel> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <StackPanel> 
        <TextBox Text="{Binding Name}" Margin="2"/> 
       </StackPanel> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 
</Window> 

代碼:

public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      DataContext = new List<Student> 
       { 
        new Student() {Name = "James Jeffery"}, 
        new Student() {Name = "Sian Ellis"}, 
        new Student() {Name = "James Jeffery 2"}, 
        new Student() {Name = "Sian Ellis 2"}, 
        new Student() {Name = "James Jeffery 3"}, 
        new Student() {Name = "Sian Ellis 3"}, 
       }; 
     } 
    } 

輸出:

enter image description here

0

你不能。網格無法做到這一點。您需要使用ItemsControl或ItemsControl的一個後件。

試試這個教程:http://www.galasoft.ch/mydotnet/articles/article-2007041201.aspx

+0

是否有可能在網格時間視圖中顯示ItemsControl?例如像數獨網格? – 2013-03-19 00:27:48

+0

@JamesJeffery是的,這是可能的。發佈你需要的截圖。 – 2013-03-19 00:31:46

+0

@HighCore http://i49.tinypic.com/2lx73w9.png – 2013-03-19 00:35:38