我注意到了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";这方面的结果:
AncestorType='System.Windows.Controls.ItemsControl',System.Windows.Data错误:4:无法找到引用'RelativeSource FindAncestor,RelativeSource AncestorLevel=‘1’绑定的源代码。BindingExpression:Path=HorizontalContentAlignment;DataItem=null;目标元素是'ListBoxItem‘(Name='');目标属性是'HorizontalContentAlignment’(键入'HorizontalAlignment') AncestorType='System.Windows.Controls.ItemsControl',System.Windows.Data错误:4:无法找到引用'RelativeSource FindAncestor,RelativeSource AncestorLevel=‘1’绑定的源代码。BindingExpression:Path=VerticalContentAlignment;DataItem=null;目标元素是'ListBoxItem‘(Name='');目标属性是'VerticalContentAlignment’(键入'VerticalAlignment')
有谁能说出这种行为的原因吗?
发布于 2015-07-30 16:33:54
这是因为ListBoxItem的默认样式包含一个带有RelativeSource的Binding,用于获取ListBoxItem对齐的包含ItemsControl的Horizontal/Vertical ContentAlignment。
就像这样:
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="{Binding HorizontalContentAlignment RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
</Style>您正在创建一个不包含在ListBoxItem中的ItemsControl,因此RelativeSource Binding无法找到该类型的祖先。
https://stackoverflow.com/questions/31728984
复制相似问题