[英]How to display datagrid in WPF?
I'm reading a word document using interop line by line. 我正在逐行阅读互操作的word文档。 Now I want the lines to be displayed on a data grid which is in XAML code. 现在,我希望这些行显示在XAML代码中的数据网格上。
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): 在返回数据表的数据上下文中创建一个属性(假设您的数据上下文实现了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: 然后在数据网格的xaml中,将ItemSource绑定到dataTable属性:
<DataGrid AutoGenerateColumns="true" ItemsSource="{Binding aTable}" >
Declare dataGrid in XAML: 在XAML中声明dataGrid:
<DataGrid x:Name="dataGrid"/>
and once your DataTable is filled you can set its DataView
as ItemsSource
of DataGrid: 并填充完DataTable之后,您可以将其DataView
设置为DataGrid的ItemsSource
:
dataGrid.ItemsSource = dt.AsDataView();
OR 要么
Declare property in proper ViewModel of type DataTable
and bind to it. 在DataTable
类型的适当ViewModel中声明属性并绑定到该属性。
You can just bind the Datatable to the Grid's ItemsSource and set AutoGeneratColumns as "true". 您可以将Datatable绑定到网格的ItemsSource并将AutoGeneratColumns设置为“ true”。
[XAML] [XAML]
<DataGrid AutoGenerateColumns="true" ItemsSource="{Binding dt}">
[c#] [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 });
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.