【发布时间】:2018-10-11 05:44:24
【问题描述】:
我尝试用自定义 DataTable 填充 ListView。我想从字符串动态创建列和行(toParse 包含行,toParse2 包含列名)。它似乎不起作用。当我启动程序时,我看到这样的东西(System.Data.DataRowView): RESULT
public partial class MainWindow : Window
{
ListView items;
string toParse = "1 12 13\n2 15 16\n3 9 14\n20 123 541235\n4 1234 567";
string toParse2 = "id value1 value2";
public MainWindow()
{
InitializeComponent();
items = GenerateListView(10,10);
}
public ListView GenerateListView(int posx, int posy)
{
ListView listview = new ListView();
DataTable table = new DataTable();
string[] columnNames = toParse2.Split(' ');
foreach (string name in columnNames) table.Columns.Add(name);
string[] lines = toParse.Split('\n');
foreach(string line in lines) {
string[] values = line.Split(' ');
if (values.Length==columnNames.Length)
{
DataRow row = table.NewRow();
table.Rows.Add(row);
for (int i=0; i<values.Length; i++)
{
row[i] = values[i];
}
}
}
listview.ItemsSource = table.DefaultView;
this.grid1.Children.Add(listview);
return listview;
}
}
此外,当我调试表时,似乎行数确实有效,但列表为空(?)。
【问题讨论】:
-
你能分享一下你的观点吗?
-
我说我希望它在 c# 声明中而不是在 xaml 中动态生成。 -
ListView没有任何基于DataTable生成列布局的自动机制。您可以手动生成列或使用DataGrid,它可以自动生成列。 -
@SolisQQ,我已经为此添加了答案。请检查一下,让我知道它是否适合您。