我如何绑定一个List< CustomObject>一个WPF的DataGrid? [英] How do I bind a List<CustomObject> to a WPF DataGrid?

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

问题描述

我新的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?

推荐答案

如果你不希望你的列表将被然后重新创建你可以用同样的方法,因为你以前用过的Asp.Net(而不是数据源这个属性在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;

但是,如果你想更换你的列表新的集合实例,那么你应该考虑使用绑定

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

这篇关于我如何绑定一个List&LT; CustomObject&GT;一个WPF的DataGrid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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