简体   繁体   中英

WPF binding to DataGrid - displaying data

I have a little problem, I know its probably trivial.

Here is my car collection :

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)
    {

    }
}

And i want to bind this to my 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>

The data is loaded to my DataGrid because I can see Columns names and 6 rows, but they are fully empty and have no idea what im doing wrong :(

You forgot to set the properties in constructor .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM