0

I have a class called Products with a property called Name. I'm trying to bind a list of Products to a ListBox named disp_products and then display the each Name in disp_products. The binding works fine, but when I run the code, blank items are put in disp_products.

Here's what I mean

This is what I have got for the XAML.

<ListBox x:Name="disp_products">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
 </ListBox>

And here's the C# code:

    public MainWindow()
    {
        InitializeComponent();

        ObservableCollection<Product> prods = new ObservableCollection<Product>();
        prods.Add(new Product(1, "Product Name 1", 33.2, 1));
        prods.Add(new Product(2, "Product Name 2", 12.1, 1));
        disp_products.ItemsSource = prods;
    }

What I want are entries "Product Name 1" and "Product Name 2" displayed in the ListBox disp_products.

Any help would be appreciated!

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
  • When only want to show one property then just use the `DisplayMemberPath` instead of setting the `ItemTemplate`. ``. I assume your `Product` class does have a property called `Name` – Nawed Nabi Zada Jun 24 '20 at 06:12
  • Make sure that `Name` is actually a public property, not a field. You should observe any data binding error messages in the Output Window in Visual Studio when you debug your application. – Clemens Jun 24 '20 at 07:38
  • hi man , i really don't understand the answer if you can explain, please! thank you – itjuba Dec 07 '20 at 02:11

0 Answers0