Matthieu
Matthieu

Reputation: 15

WPF Listview not displaying when I add an item

I'm trying to add items dynamically to a listview in WPF, but I don't know why any items are displaying. Though it was a refresher problem, so I tried to use some ObservableCollection but it didn't work. I'm getting informations in two textblocs, and want them to show in the listview when I click on a button.

Could you help me understund the problem ?

My WPF with the listview

<ListView Name="listview" Margin="0 10 0 0" Height="150" ItemsSource="{Binding Recette}">
            <ListView.View>
                <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding nomP}" Header="Nom" Width="250"/>
                    <GridViewColumn DisplayMemberBinding="{Binding quantP}" Header="Quantité" Width="100"/>

                </GridView>
            </ListView.View>
</ListView>

My .cs :

public List<Produits> Recette { get; set; }
    public AjoutRecette()
    {
        InitializeComponent();
    }

    private void btnAjoutProd_Click(object sender, RoutedEventArgs e)
    {
        string nomP = combobProd.Text;
        int quantP = int.Parse(txtbQuantité.Text);
        Produits prod = new Produits(nomP, quantP);
        Recette.Add(prod);
    }

and here's what i've already tried with the ObersvableCollection :

public ObservableCollection<Produits> Recette { get; set; }
    public AjoutRecette()
    {
        InitializeComponent();
    }

    private void btnAjoutProd_Click(object sender, RoutedEventArgs e)
    {
        Recette = new ObservableCollection<Produits>();
        string nomP = combobProd.Text;
        int quantP = int.Parse(txtbQuantité.Text);
        Produits prod = new Produits(nomP, quantP);
        Recette.Add(prod);
    }

Thanks a lot !

Upvotes: 1

Views: 586

Answers (1)

madbadger
madbadger

Reputation: 644

To make it work, please check the following points:

  1. Please change Recette to be of type ObservableCollection<Produits> instead of List<Produits>. You would need to adjust the property type as well as the part of code where you instantiate the collection. You can simply do:

    public ObservableCollection<Produits> Recette { get; set; } = new ObservableCollection<Produits>();
    
  2. Make sure that the DataContext property is set correctly. One way of doing that would be to set DataContext in the constructor of AjoutRecette:

    public AjoutRecette()
    {
        InitializeComponent();
        listview.DataContext = this;
    }
    
  3. Also, please make sure that properties nomP and quantP are present in the Produits class.

Good luck!

Upvotes: 1

Related Questions