ListBoxItem produces "System.Windows.Data Error: 4" binding error ListBoxItem produces "System.Windows.Data Error: 4" binding error wpf wpf

ListBoxItem produces "System.Windows.Data Error: 4" binding error


The easiest way to solve this is to ensure that your Listbox has a ItemContainerStyle. See the following example:

<ListBox x:Name="RecentItemsListBox" Grid.Row="1" BorderThickness="0" Margin="2,0,0,0" SelectionChanged="RecentItemsListBox_SelectionChanged">    <ListBox.ItemContainerStyle>        <Style TargetType="{x:Type ListBoxItem}">            <Setter Property="HorizontalContentAlignment" Value="Left"/>            <Setter Property="VerticalContentAlignment" Value="Center"/>        </Style>    </ListBox.ItemContainerStyle>...</ListBox>

What happens is that your Items are being created, and by default they look for parent's property which isn't defined. Explicitly defining it will solve this problem.

I had the same issue using a TreeView and changing the bound source for these templates would cause those warnings.


The answer over here resolved this issue for me:

ListBox with Grid as ItemsPanelTemplate produces weird binding errors

Defining a top-level style (in my App.xaml) targeting the problem type "fixed" the issue for me. Here's a style that should work for you:

<Style TargetType="{x:Type ListBoxItem}">     <Setter Property="HorizontalContentAlignment" Value="Left" />     <Setter Property="VerticalContentAlignment" Value="Top" /></Style>

In my case, I was creating some TreeViewItems and then binding my TreeView to the created items. The binding error was occurring because the TreeViewItem's binding was being resolved before they were being added to the TreeView. The correct solution was to not create a TreeViewItem, but instead create a class that contained the data I needed (Header and Items). Just relaying my situation in case there are parallels with your own.


Another workaround that worked for me was to suppress these errors (actually, it seems more appropriate to call them warnings) by setting the data binding source switch level as critical in constructor of the class or a top level window -

#if DEBUG         System.Diagnostics.PresentationTraceSources.DataBindingSource.Switch.Level =        System.Diagnostics.SourceLevels.Critical;#endif

Ref.: How to suppress the System.Windows.Data Error warning message

Update: This is not the best solution but for warnings which are harmful this looks good to me.