WPF8 / C# - 将数据绑定到网格

时间:2013-03-18 23:18:59

标签: c# windows-phone-8

我知道我发布了这个问题,但是在我的上一个问题上接受了答案,并且通过文章后我意识到这不是我想要的答案。我再次发布了一些示例代码。

我想用一个集合中的Data填充Grid(而不是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上的每个示例都显示了ListViews等。我想填充网格,只有网格。

有关如何实现这一目标的任何建议吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

你不能。网格无法做到这一点。您需要使用ItemsControl或ItemsControl的desendant。

试用本教程:http://www.galasoft.ch/mydotnet/articles/article-2007041201.aspx

相关问题