Item Template Not Using Data Context

RogerSchlueter-7899 1,591 Reputation points
2024-07-27T22:51:49.1966667+00:00

Here is code for WPF window (omitting irrelevant stuff):

XAML

<ListBox
	x:Name="lbxEvents">
	<ListBox.ItemTemplate>
		<DataTemplate>
			<TextBox
				BorderThickness="0"
				FontWeight="SemiBold"
				Padding="0,2,0,2"
				Text="{Binding Path=Title, Mode=OneWay}" />
		</DataTemplate>
	</ListBox.ItemTemplate>
</ListBox>

Code behind:

Public Sub New()
	InitializeComponent()
	DataContext = Me
End Sub

Public Structure evt
	Public Beginning As Date
	Public CategoryID As Integer
	Public Title As String
End Structure

Private Sub PopulateUpcomingEvents()
	Dim ev As evt
	Dim evts As New List(Of evt)
	<<Events are populated correctly>>
	lbxEvents.ItemsSource = evts
End Sub

Error message:

System.Windows.Data Error: 40 : BindingExpression path error: 'Title' property not found on 'object' ''evt' (HashCode=-13885767)'. BindingExpression:Path=Title; DataItem='evt' (HashCode=-13885767); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String')

I cannot see why this error occurs.

Developer technologies | Windows Presentation Foundation
0 comments No comments
{count} votes

Answer accepted by question author
  1. Hui Liu-MSFT 48,711 Reputation points Microsoft External Staff
    2024-07-29T06:52:46.88+00:00

    Hi,@RogerSchlueter-7899. Welcome to Microsoft Q&A.

    The problem may be due to ListBox item binding requiring the property of the bound object to be a public field or property. In your structure, evt uses public fields instead of properties, which is causing the binding to fail. To resolve this, you could convert the fields to properties.

    	Public Class evt
    
    		Public Property Beginning As Date
    
    		Public Property CategoryID As Integer
    
    		Public Property Title As String
    
    	End Class
    
    

    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.

1 additional answer

Sort by: Most helpful
  1. Viorel 126.1K Reputation points
    2024-07-28T04:56:04.5766667+00:00

    Try a property: Public Property Title As String. Make sure that PopulateUpcomingEvents is executed.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.