Help with ListBox Binding

RogerSchlueter-7899 1,236 Reputation points
2023-11-07T06:22:36.2566667+00:00

This is a distillation of a problem I am having with a larger application.

<Window x:Class="MainWindow"
    ....
    <ListBox
        ItemsSource="{Binding Source=Widgets}"
	    SelectedValuePath="WidgetID"
	    DisplayMemberPath="Name"
    </ListBox>
</Window>

and

Class MainWindow
    Public Property Widgets as new ObservableCollection(Of Widget)
	
	Public Sub New
	    InitializeComponent()
		DataContext = Me
	End Sub
	....
End Class

This causes Binding Path errors because the DisplayMemberPath ("Name") is not a member of Widgets. However I don't know how to fix the problem.

Also note that this is NOT Visual Basic for Applications but rather VB.NET.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,700 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,637 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 47,101 Reputation points Microsoft Vendor
    2023-11-07T09:51:47.49+00:00

    Hi,@Roger Schlueter. Welcome to Microsoft Q&A. What is the code of your Widget class? You could try to refer to the sample code below to see if it helps you.

      <ListBox ItemsSource="{Binding Widgets}" 
                     SelectedValuePath="WidgetID" 
                     DisplayMemberPath="Name" />
    

    Codebehind:

    Imports System.Collections.ObjectModel
    
    Class MainWindow
        Public Property Widgets As New ObservableCollection(Of Widget)()
    
        Public Sub New()
            InitializeComponent()
            ' Add some sample data to the collection
            Widgets.Add(New Widget() With {.WidgetID = 1, .Name = "Widget 1"})
            Widgets.Add(New Widget() With {.WidgetID = 2, .Name = "Widget 2"})
            ' Add more items as needed
            DataContext = Me
        End Sub
    End Class
    Public Class Widget
        Public Property WidgetID As Integer
        Public Property Name As String
        ' Other properties
    End Class
    

    The result:

    If the problem still exists, can you share more code with me for analysis?


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful