我正在尝试将DataGrid
的WinForms代码移植到WPF应用程序,我已经尝试了几种解决方案,但还没有任何工作。
我想要移植的代码:
this.dataGridView1.Enabled = true;
this.dataGridView1.RowCount = 0x12;
for (int i = 0; i < 0x12; i++)
{
this.dataGridView1.Update();
this.dataGridView1.Rows[i].Cells[0].Value = i;
this.dataGridView1.Rows[i].Cells[1].Value = this.GetName(i);
}
我已经尝试过的解决方案:
XAML:
<DataGrid Name="DataGridView1" ItemsSource="{Binding}" AutoGenerateColumns="False" Margin="176,70,409,92" SelectionChanged="DataGridView1_SelectionChanged" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding ClientID}" Header="#"/>
<DataGridTextColumn Binding="{Binding ClientName}" Header="Client Name"/>
</DataGrid.Columns>
</DataGrid>
C#:
#1:
if (dataGridView1.RowCount == 1)
{
dataGridView1.Rows.Add(11);
}
for (uint i = 0; i < 12; i++)
{
dataGridView1[0, Convert.ToInt32(i)].Value = i;
dataGridView1[1, Convert.ToInt32(i)].Value = ClientNames(i);
}
}
#2:
DataTable dt = new DataTable();
DataColumn column;
column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "S1";
dt.Columns.Add(column);
column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "S2";
dt.Columns.Add(column);
if (dt.Items.Count == 1)
{
dt.Rows.Add(11);
}
for (uint i = 0; i < 12; i++)
{
DataRow row = myDT.NewRow();
row["S1"] = i.ToString();
row["S2"] = ClientNames(i);
dt.Rows.Add(row);
}
}
#3:
DataRowView rowView = dataGridView1.SelectedItem as DataRowView;
dataGridView1.Enabled = true; dataGridView1.Items.Count = 12;
for (int i = 0; i < 12; i++)
{
dataGridView1.Update();
rowView.Rows[i].Cells[0].Value = i;
rowView.Rows[i].Cells[1].Value = GetName(i);
}
我现在正在谷歌上搜索近3周,所以我希望有人可以帮助我。
答案 0 :(得分:0)
您可以写下以下内容:
public class DataGridViewModel
{
public string Id{get;set;}
public string Value{get;set;
}
...
for (int i = 0; i < 0x12; i++)
{
this.Models.Add(new DataGridViewModel(){Id=i,Value=GetName(i)};
}
在XAML中:
<DataGrid Name="DataGridView1" ItemsSource="{Binding Models}" AutoGenerateColumns="False" Margin="176,70,409,92" SelectionChanged="DataGridView1_SelectionChanged" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Id}" Header="#"/>
<DataGridTextColumn Binding="{Binding Value}" Header="Client Name"/>
</DataGrid.Columns>
</DataGrid>
如果需要,请不要忘记实施NotifyPropertyChanged。如果您需要进一步解释,请随时询问,我在上面的代码中只显示了基本的想法。