我注意到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:路径= HorizontalContentAlignment;的DataItem = NULL; target元素是'ListBoxItem'(Name =''); target属性是'HorizontalContentAlignment'(类型'HorizontalAlignment')
System.Windows.Data错误:4:无法找到与引用'RelativeSource FindAncestor绑定的源,AncestorType ='System.Windows.Controls.ItemsControl',AncestorLevel ='1''。 BindingExpression:路径= VerticalContentAlignment;的DataItem = NULL; target元素是'ListBoxItem'(Name =''); target属性是'VerticalContentAlignment'(类型'VerticalAlignment')
有人能说出导致这种行为的原因吗?
答案 0 :(得分:1)
这是因为ListBoxItem
的默认样式包含Binding
RelativeSource
来获取包含Horizontal/Vertical
的{{1}} ContentAlignment
ItemsControl
的路线。
这样的事情:
ListBoxItem
您正在创建<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="{Binding HorizontalContentAlignment RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
</Style>
未包含的ListBoxItem
,因此ItemsControl
RelativeSource
无法找到该类型的祖先。