如何使用C#WPF将文本文件绑定到数据网格?这个想法是在文本文件中有一行显示为datagrid中的一行。C#WPF将文本文件绑定到datagrid
0
A
回答
4
我不认为你可以直接绑定文本到DataGrid
什么,但是你可以做的是一个客体绑定到DataGrid
创建代表文本文件的客体。
-- content --
text1, param1, param2
text2, param1, param2
class OneLine{
string text {get;set;}
string param { get;set; }
...
}
然后,您可以使用BindingList(主要是List)将这些对象绑定到数据网格。魔法在于对象的属性。 BindingList将尝试获取对象的每个属性并将它们显示在网格中。
BindingList<OneLine> myList = new BindingList<OneLine>();
myList.Add(oneObject);
DataGrid myGrid = new DataGrid();
myGrid.DataSource = myList;
1
在项目中,我用下面的办法
创建表示在文本文件中的行例如
public class cls_syslog_record { public DateTime? f1 {get;set;} public string f2 {get;set;} public string f3 {get;set;} public string f4 {get;set;} }
创建IEnumerable的是,用作源的DataGrid
类public IEnumerable<cls_syslog_record> get_line_seq_text() { cls_mvs_syslog_parser parser = new cls_mvs_syslog_parser(); foreach (string record_line in File.ReadLines(this.filename)) { cls_syslog_record text_record = parser.parse_syslog_text(record_line); if (text_record == null) { continue; } yield return text_record; } }
设置我的IEnumerable对象作为源
static private DataGrid make_text_viewer(string p_filename) { logger.Debug("start"); DataGrid table_viewer; cls_file_line_seq fl_seq = new cls_file_line_seq(p_filename); table_viewer = new DataGrid(); table_viewer.CanUserAddRows = false; table_viewer.CanUserDeleteRows = false; table_viewer.Columns.Add(create_column("Date Time", "timestamp")); table_viewer.Columns.Add(create_column("LPAR Name", "lpar_name")); table_viewer.Columns.Add(create_column("JOB ID", "job_id")); table_viewer.Columns.Add(create_column("Message", "message")); table_viewer.HeadersVisibility = DataGridHeadersVisibility.All; table_viewer.ItemsSource = fl_seq.get_line_seq_text(); return table_viewer; }
然后设置结合
static private DataGridColumn create_column(string header, string p_property_name) { DataGridTextColumn column = new DataGridTextColumn(); column.Header = header; column.Binding = new Binding(p_property_name); return column; }
相关问题
- 1. 将WPF TextBlock绑定到文本文件
- 2. 从Datagrid(WPF)绑定文本框
- 3. 绑定WPF DataGrid文本列的前景
- 4. 如何将文本块绑定到WPF中DataGrid列的总和?
- 5. 将文本框文本绑定到wpf中的xml文件
- 6. WPF绑定到CellStyle的DataGrid上下文
- 7. C#WPF绑定列表到DataGrid
- 8. wpf绑定文本
- 9. WPF DataGrid绑定
- 10. 将外键绑定到Datagrid(WPF/EF)
- 11. 将ViewModel命令绑定到WPF DataGrid
- 12. WPF:将DataGrid列标题绑定到ViewModel
- 13. 将DataTable绑定到DataGrid。 WPF MVVM
- 14. 绑定文本菜单到DataGrid列
- 15. WPF Datagrid绑定到xml
- 16. 问题绑定到WPF Datagrid
- 17. WPF C#按钮绑定和文本框到按钮绑定
- 18. WPF:将文本块绑定到文本框
- 19. 将对象绑定到文本框c#
- 20. 将动态查询绑定到DataGrid C#WPF
- 21. 将文本框绑定到文本框
- 22. WPF DataTemplate文本块绑定
- 23. WPF绑定DataTable列到文本框
- 24. WPF Datagrid组扩展文本 - 如何绑定?
- 25. 的数据绑定WPF DataGrid中(C#4.0)
- 26. 将WPF DataGrid控件绑定到System.Data.DataTable对象?
- 27. 将文本框的文本属性绑定到MainWindow上定义的变量WPF
- 28. 将文件绑定到longlistselector
- 29. 将许多XML文件绑定到Datagrid的行
- 30. WPF C#:从文本文件