WPF绑定到DataGrid - 显示数据

时间:2014-07-03 20:29:29

标签: c# wpf binding

我有一点问题,我知道这可能是微不足道的。

这是我的车系列:

public class CarCollection : ObservableCollection<Car>
{
    public CarCollection()
    {
        Add(new Car("BMW", "X6", 250000, "Berlin"));
        Add(new Car("BMW", "X4", 170000, "Berlin"));
        Add(new Car("Audi", "A4", 55000, "Warszawa"));
        Add(new Car("Audi", "A5", 75000, "Blabla"));
        Add(new Car("Audi", "A6", 120000, "Berlin"));
        Add(new Car("Seat", "Ibiza", 22000, "Barcelona"));
    }
}

public class Car
{
    public string Company { get; set; }
    public string Model { get; set; }
    public int Price { get; set; }
    public string City { get; set; }

    public Car()
    { }

    public Car(string company, string model, int price, string city)
    {

    }
}

我想将它绑定到我的DataGrid:

<Window x:Class="DataGrid.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:DataGrid"
    Title="MainWindow" Height="350" Width="525">
   <Window.DataContext>
       <local:CarCollection/>
   </Window.DataContext>
   <Grid>
       <DataGrid x:Name="myDataGrid" ItemsSource="{Binding}"/>
   </Grid>
</Window>

数据被加载到我的DataGrid,因为我可以看到列名和6行,但它们是完全空的,不知道我做错了什么:(

1 个答案:

答案 0 :(得分:4)

您忘记在构造函数中设置属性

public Car(string company, string model, int price, string city)
{
    Company = company;
    Model = model;
    Price = price;
    City = city;
}
相关问题