2
votes

I have noticed this strange thing with ListBoxItem, even if you don't actually do anything with the ListBoxItem you created it will cause 2 binding errors if it's content is not null. Note that I do not create any bindings, and I have posted all the code you need to reproduce those errors.

ListBoxItem li = new ListBoxItem();

or

ListBox lb = new ListBox();
ListBoxItem li = new ListBoxItem();
li.Content = "Something";
lb.Items.Add(li);

Won't cause any errors, but

ListBoxItem li = new ListBoxItem();
li.Content = "Something";

Results in this:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'ListBoxItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'ListBoxItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

Could anyone tell what causes this behavior?

1
Where is the XAML for your binding?Glen Thomas
No xaml and no bindings.FINDarkside

1 Answers

2
votes

It is because the default style for ListBoxItem contains a Binding with RelativeSource to get the Horizontal/Vertical ContentAlignment of the containing ItemsControl for the ListBoxItem's alignments.

Something like this:

<Style TargetType="ListBoxItem">
    <Setter Property="HorizontalAlignment" Value="{Binding HorizontalContentAlignment RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
</Style>

You are creating a ListBoxItem that is not contained in an ItemsControl, so the RelativeSource Binding fails to find an ancestor of that type.