如何绑定 List<CustomObject>到 WPF 数据网格? [英] How do I bind a List&lt;CustomObject&gt; to a WPF DataGrid?

查看:18
本文介绍了如何绑定 List<CustomObject>到 WPF 数据网格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 WPF 的新手,想做一些基本的数据绑定.我有一个 CustomObject 列表,想将它绑定到 DataGrid.

I'm new to WPF and want to do some basic databinding. I have a List of a CustomObject and want to bind it to a DataGrid.

MainWindow.xaml.cs

MainWindow.xaml.cs

   using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;

    namespace WpfApplication1
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                List<ArticleItem> list = new List<ArticleItem>() 
                {
                new ArticleItem(){ ID=3, Title="test", ViewCount=5},
                new ArticleItem(){ ID=3, Title="test", ViewCount=5},
                new ArticleItem(){ ID=3, Title="test", ViewCount=5},
                new ArticleItem(){ ID=3, Title="test", ViewCount=5},
                };
            }
        }

        public class ArticleItem 
        {
            public int ID { get; set; }
            public int ViewCount { get; set; }
            public String Title { get; set; }
        }
    }

这是我的网格的样子:

<DataGrid Height="179" HorizontalAlignment="Left" Margin="54,65,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="382">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID"/>
            <DataGridTextColumn Header="ViewCount" />
        <DataGridTextColumn Header="Title" />
    </DataGrid.Columns>
</DataGrid>

我已经习惯了来自 ASP.Net 的数据绑定,我可以很容易地说:

I'm used to the databinding from ASP.Net, where I can easily say:

this.dataGrid1.DataSource = list;

我必须如何在 WPF 中继续?

How must I proceed in WPF?

推荐答案

如果您不希望您的 list 会被重新创建,那么您可以使用与用于 Asp 相同的方法.Net(而不是 DataSource 这个属性在 WPF 中通常被命名为 ItemsSource):

if you do not expect that your list will be recreated then you can use the same approach as you've used for Asp.Net (instead of DataSource this property in WPF is usually named ItemsSource):

this.dataGrid1.ItemsSource = list;

但是如果你想用新的集合实例替换你的list,那么你应该考虑使用databinding.

But if you would like to replace your list with new collection instance then you should consider using databinding.

这篇关于如何绑定 List<CustomObject>到 WPF 数据网格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆