WPF Application - can't display data from a list in a datagrid

前提是你 提交于 2020-01-07 04:51:09

问题


I'm a newbie with WPF and c# and have a (probably very simple) problem.

I'm coding a small application, and i'm trying to read data from a database, format it into a list, and display in a datagrid. Ive debugged it, and it I've successfully read the database, and all the data is in the list (cd_list), but it's not passing the data to the datagrid.

Below is my XAML:

<DataGrid Name="DataGrid" AutoGenerateColumns="false" RowHeaderWidth="0" Width="240" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" ></DataGridTextColumn>
                <DataGridTextColumn Header="Details"></DataGridTextColumn>
                <DataGridTextColumn Header="Employee"></DataGridTextColumn>
                <DataGridTextColumn Header="Date"></DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>

My code behind file does InitializeComponent, then does some work to get the data from a DB, and put it in a list of call_detail objects:

public class call_details
{
    public string name;
    public string details;
    public string employee;
    public string date;

    public call_details()
    {
    }
}

Declare list & call detail objects

   public call_details cd_rec = new call_details();
   public List<call_details> cd_list = new List<call_details>();

Add records to the list

   cd_list.Add(cd_rec);           

After this is done, I am trying to give the ItemsSource so that the data will show in the Datagrid, and have the following:

DataGrid.ItemsSource = cd_list;

but its not working. In the GUI, the Datagrid shows a grid, with the correct number of records that I expect, but they are all blank.So I guess that it is passing some info, just not the actual data. It's probably a silly mistake which I have made due to being a novice, but I can't find anything else out there to help me.

Anyone?


回答1:


All those fields need to be exposed as public properties with at least a getter (this is a requirement of the binding-system). Then you need to bind to the properties or just use the auto-generated columns.

public string Name { get; private set; }
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />

If you are new to WPF i highly recommend reading some of the articles on MSDN. e.g. the Data Binding Overview.



来源:https://stackoverflow.com/questions/6011297/wpf-application-cant-display-data-from-a-list-in-a-datagrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!