c# - WPF8/C# - 将数据绑定(bind)到网格

标签 c# windows-phone-8

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

我想用集合中的数据填充网格(不是数据网格)。这是我所拥有的,但它不起作用。如果我删除集合并将 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 等。我想填充一个网格,并且只填充一个网格。

关于如何实现这一点有什么建议吗?

最佳答案

正如另一个答案中提到的,您需要一个 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

关于c# - WPF8/C# - 将数据绑定(bind)到网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15488773/

相关文章:

c# - 服务器为 Socket() 调用注册客户端 ID 两次

mysql - 如何从 Windows Phone 8 应用程序连接到远程 MySQL 数据库?

C# Random.Next - 从不返回上限?

c# - .NET 在不同时区和不同区域设置的 SQL 中存储 DateTime

C# MySQL 连接 3 个表

windows-phone-8 - ReBind-Reload LongListMultiSelector 时崩溃

internet-explorer - 在 Windows Phone 8 中远程调试网站?

c# - Windows 重启后 Postgresql 特定查询失败一次

javascript - 导航到 Windows 应用商店应用程序中的另一个 html

c# - 文本框只能大写