这是我第一次使用C#DataGrid控件(以及我的第一个c#项目之一)而且我很难让DataGrid控件以编程方式填充。每次我用两列添加一行时,它们都是空白的。
XAML代码
<DataGrid ItemsSource="{Binding}" x:Name="resultsDataGrid" HorizontalAlignment="Left" Margin="10,454,0,0" VerticalAlignment="Top" Height="199" Width="499">
<DataGrid.Columns>
<DataGridTextColumn Header="Url"/>
<DataGridTextColumn Header="404"/>
</DataGrid.Columns>
</DataGrid>
CS代码
resultsDataGrid.Items.Add(new object[] { detailsOfFind[0], detailsOfFind[1] });
我一直在查看示例,我可以看到你必须绑定到数据集/数据库/源,但是当我以编程方式添加这些时我不知道如何做到这一点?我在这里做错了什么?
答案 0 :(得分:0)
DataGrid有一个名为AutoGenerateColumns
的属性,默认为true。这将自动为每个属性创建一个列,其中包含属性名称的标题。但是,由于您使用的是匿名类型,因此您没有属性名称。这就是你的空白栏的来源。
解决方案是将AutoGenerateColumns="False"
添加到您的<DataGrid>
参数中。
答案 1 :(得分:0)
试试这个:
XAML代码:
<Grid Height="396" Name="grid1" Width="565">
<DataGrid AutoGenerateColumns="False" Height="170" HorizontalAlignment="Left" Margin="12,85,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="541" />
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="12,37,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
CS代码:
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
// Add Columns to the dataGrid
DataGridTextColumn c1 = new DataGridTextColumn();
c1.Header = "Person ID";
c1.Binding = new Binding("ID");
c1.Width = 110;
dataGrid1.Columns.Add(c1);
DataGridTextColumn c2 = new DataGridTextColumn();
c2.Header = "First Name";
c2.Width = 110;
c2.Binding = new Binding("FirstName");
dataGrid1.Columns.Add(c2);
DataGridTextColumn c3 = new DataGridTextColumn();
c3.Header = "Last Name";
c3.Width = 110;
c3.Binding = new Binding("LastName");
dataGrid1.Columns.Add(c3);
// Create the Data
List<Person> myData = new List<Person>();
myData.Add(new Person() { ID = 5, FirstName = "Jamie", LastName = "White" });
myData.Add(new Person() { ID = 10, FirstName = "Mike", LastName = "Smith" });
myData.Add(new Person() { ID = 25, FirstName = "Joe", LastName = "Yang" });
// Pass the data to the dataGrid
dataGrid1.ItemsSource = myData;
//// OR
//dataGrid1.Items.Add(new Person() { ID = 5, FirstName = "Jamie", LastName = "Weir" });
//dataGrid1.Items.Add(new Person() { ID = 10, FirstName = "Mike", LastName = "Smith" });
//dataGrid1.Items.Add(new Person() { ID = 25, FirstName = "Joe", LastName = "Yang" });
// Modify a cell
((Person)dataGrid1.Items[1]).LastName = "Schmidt";
}
}
public class Person
{
public int ID { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
}
}