简体   繁体   English

如何将List <CustomObject>绑定到WPF DataGrid?

[英]How do I bind a List<CustomObject> to a WPF DataGrid?

I'm new to WPF and want to do some basic databinding. 我是WPF的新手,想要做一些基本的数据绑定。 I have a List of a CustomObject and want to bind it to a DataGrid. 我有一个CustomObject的列表,并希望将其绑定到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; }
        }
    }

This is how my grid looks like: 这就是我的网格的样子:

<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>

I'm used to the databinding from ASP.Net, where I can easily say: 我已经习惯了ASP.Net的数据绑定,我可以很容易地说:

this.dataGrid1.DataSource = list;

How must I proceed in WPF? 我该如何进行WPF?

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 ): 如果您不希望重新创建list那么您可以使用与Asp.Net相同的方法(而不是DataSource ,WPF中的此属性通常名为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 ,那么您应该考虑使用databinding

You should do it in the xaml code: 你应该在xaml代码中做到这一点:

<DataGrid ItemsSource="{Binding list}" [...]>
  [...]
</DataGrid>

I would advise you to use an ObservableCollection as your backing collection, as that would propagate changes to the datagrid, as it implements INotifyCollectionChanged . 我建议你使用ObservableCollection作为后台集合,因为它会将更改传播到datagrid,因为它实现了INotifyCollectionChanged

Actually, to properly support sorting, filtering, etc. a CollectionViewSource should be used as a link between the DataGrid and the list, like this: 实际上,为了正确支持排序,过滤等,CollectionViewSource应该用作DataGrid和列表之间的链接,如下所示:

<Window.Resources>
  <CollectionViewSource x:Key="ItemCollectionViewSource" CollectionViewType="ListCollectionView"/>
</Window.Resources>   

The DataGrid line looks like this: DataGrid行如下所示:

<DataGrid
  DataContext="{StaticResource ItemCollectionViewSource}"
  ItemsSource="{Binding}"
  AutoGenerateColumns="False">  

In the code behind, you link CollectionViewSource with your link. 在后面的代码中,您将CollectionViewSource与您的链接相关联。

CollectionViewSource itemCollectionViewSource;
itemCollectionViewSource = (CollectionViewSource)(FindResource("ItemCollectionViewSource"));
itemCollectionViewSource.Source = itemList;

For detailed example see my article on CoedProject: http://www.codeproject.com/Articles/683429/Guide-to-WPF-DataGrid-formatting-using-bindings 有关详细示例,请参阅我在CoedProject上的文章: http//www.codeproject.com/Articles/683429/Guide-to-WPFvalsGrid-formatting-using-bindings

You dont need to give column names manually in xaml. 您不需要在xaml中手动提供列名。 Just set AutoGenerateColumns property to true and your list will be automatically binded to DataGrid. 只需将AutoGenerateColumns属性设置为true,您的列表将自动绑定到DataGrid。 refer code. 参考代码。 XAML Code: XAML代码:

<Grid>
    <DataGrid x:Name="MyDatagrid" AutoGenerateColumns="True" Height="447" HorizontalAlignment="Left" Margin="20,85,0,0" VerticalAlignment="Top" Width="799"  ItemsSource="{Binding Path=ListTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  CanUserAddRows="False"> </Grid>

C# C#

Public Class Test 
{
    public string m_field1_Test{get;set;}
    public string m_field2_Test { get; set; }
    public Test()
    {
        m_field1_Test = "field1";
        m_field2_Test = "field2";
    }
    public MainWindow()
    {

        listTest = new List<Test>();

        for (int i = 0; i < 10; i++)
        {
            obj = new Test();
            listTest.Add(obj);

        }

        this.MyDatagrid.ItemsSource = ListTest;

        InitializeComponent();

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM