如果内容不为空,则未使用的ListBoxItem导致绑定错误

时间:2015-07-30 16:14:20

标签: c# wpf

我注意到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:路径= Horizo​​ntalContentAlignment;的DataItem = NULL; target元素是'ListBoxItem'(Name =''); target属性是'Horizo​​ntalContentAlignment'(类型'Horizo​​ntalAlignment')

     

System.Windows.Data错误:4:无法找到与引用'RelativeSource FindAncestor绑定的源,AncestorType ='System.Windows.Controls.ItemsControl',AncestorLevel ='1''。 BindingExpression:路径= VerticalContentAlignment;的DataItem = NULL; target元素是'ListBoxItem'(Name =''); target属性是'VerticalContentAlignment'(类型'VerticalAlignment')

有人能说出导致这种行为的原因吗?

1 个答案:

答案 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无法找到该类型的祖先。