2013-03-18 117 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