简体   繁体   中英

How to display datagrid in WPF?

I'm reading a word document using interop line by line. Now I want the lines to be displayed on a data grid which is in XAML code.

DataTable dt = new DataTable();
dt.Columns.Add("Text");


for (int i = 0; i < doc.Sentences.Count; i++)
{
    //string temp = doc.Paragraphs[i + 1].Range.Text.Trim();
    string temp = doc.Sentences[i + 1].Text;
    if (temp != string.Empty)
    {
        data.Add(temp);
        dt.Rows.Add(new object[] { data });
    }
}

Create a property in your data context returning your DataTable (assuming your datacontext implements INotifyPropertyChanged):

    private DataTable _aTable;
    public DataTable aTable
    {
        get
        {
            return _aTable;
        }
        set
        {
            _aTable= value;
            RaisePropertyChanged("aTable");
        }
    }

Then in your xaml for the datagrid bind ItemSource to your dataTable property:

    <DataGrid  AutoGenerateColumns="true" ItemsSource="{Binding aTable}" >

Declare dataGrid in XAML:

<DataGrid x:Name="dataGrid"/>

and once your DataTable is filled you can set its DataView as ItemsSource of DataGrid:

dataGrid.ItemsSource = dt.AsDataView();

OR

Declare property in proper ViewModel of type DataTable and bind to it.

You can just bind the Datatable to the Grid's ItemsSource and set AutoGeneratColumns as "true".

[XAML]

<DataGrid  AutoGenerateColumns="true" ItemsSource="{Binding dt}">

[c#]

private DataTable _dt;
public DataTable dt
{
    get
    {
        return _dt;
    }
    set
    {
        _dt= value;
    }
}

Void Load()
{
  dt.Columns.Add("Text");

  for (int i = 0; i < doc.Sentences.Count; i++)
  {
    string temp = doc.Sentences[i + 1].Text;
    if (temp != string.Empty)
    { 
      data.Add(temp);
      dt.Rows.Add(new object[] { data });
    } 
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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