Listview show two fields in each row

0

Visual Studio Community 2015 + SQLite + Entity Framework

The database has 2 fields: ID and ShipType

Class for mapping the database:

namespace ImperialFleet
{
public class ShipTypeClass
{
    private string id;
    private string type;

    public ShipTypeClass(string id, string type)
    {
        this.Id = id;
        this.ShipType = type;
    }

    public string Id { get; set; }
    public string ShipType { get; set; }
}
}

Code to load the Listview

        private void button_Click(object sender, RoutedEventArgs e)
    {
        List<string> shipList = new List<string>();
        using (var db = new ImperialFleetDBEntities())
        {
            shipList = (from g in db.ShipsType select g.ShipType).ToList();

       }

        listView.Items.Clear();                   
        foreach (string str in shipList)
        {
            listView.Items.Add(str);
        }

xaml Listview

<ListView x:Name="listView" HorizontalAlignment="Left" Height="198" Margin="39,10,0,0" VerticalAlignment="Top" Width="446">
        <ListView.View>
            <GridView>
                <GridViewColumn/>
            </GridView>
        </ListView.View>
    </ListView>

How can I do to show the other column with the ID field?

(from g in db.ShipsType select g.ID).ToList()
    
asked by fedeteka 17.11.2017 в 13:23
source

1 answer

2

Try using GridViewColumn specifying the property of which you will show in the DisplayMemberBinding property in the XAML:

<ListView x:Name="listView" HorizontalAlignment="Left" Height="198" Margin="39,10,0,0" VerticalAlignment="Top" Width="446">
    <ListView.View>
        <GridView>
              <GridViewColumn Header="Id" Width="Auto" 
                            DisplayMemberBinding="{Binding Id}"/>

            <GridViewColumn Header="Shit Type" Width="Auto" 
                            DisplayMemberBinding="{Binding ShipType}"/>    
        </GridView>
    </ListView.View>
</ListView>

Each property specified in the DisplayMemberBinding represents the property of your model, so you have to ensure they have the same name.

Then to show the data you will only have to assign the collection to the property ItemsSource of the ListView:

List<string> shipList = new List<string>();
using (var db = new ImperialFleetDBEntities())
{
    listView.ItemsSourrce = db.ShipsType.ToList();
}
    
answered by 17.11.2017 / 13:52
source