Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unused ListBoxItem causing binding errors if content is not null

Tags:

c#

wpf

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?

like image 589
FINDarkside Avatar asked Feb 14 '26 18:02

FINDarkside


1 Answers

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.

like image 178
Glen Thomas Avatar answered Feb 16 '26 06:02

Glen Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!