我注意到了一个关于ListBoxItem的奇怪现象,即使你实际上不对创建的ListBoxItem进行任何操作,如果它的内容不是null,它也会导致2个绑定错误。请注意,我没有创建任何绑定,并且我已经发布了所有需要重现这些错误的代码。
ListBoxItem li = new ListBoxItem();
或者
ListBox lb = new ListBox();
ListBoxItem li = new ListBoxItem();
li.Content = "Something";
lb.Items.Add(li);
不会引起任何错误,但是
ListBoxItem li = new ListBoxItem();
li.Content = "Something";
这会产生以下结果:
System.Windows.Data错误:4:找不到引用'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错误:4:找不到引用'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')
有人能告诉我是什么原因导致了这种行为吗?