我注意到 ListBoxItem 有这个奇怪的事情,即使您实际上没有对您创建的 ListBoxItem 做任何事情,如果它的内容不为空,它也会导致 2 个绑定(bind)错误。请注意,我没有创建任何绑定(bind),并且我已经发布了重现这些错误所需的所有代码。
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 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')
谁能说出是什么导致了这种行为?
最佳答案
这是因为 ListBoxItem
的默认样式包含一个 Binding
和 RelativeSource
来获取 Horizontal/Vertical
ListBoxItem
的对齐方式的包含 ItemsControl
的 ContentAlignment
。
像这样:
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="{Binding HorizontalContentAlignment RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
</Style>
您正在创建一个未包含在 ItemsControl
中的 ListBoxItem
,因此 RelativeSource
Binding
无法找到那个类型的祖先。
关于c# - 如果内容不为空,未使用的 ListBoxItem 会导致绑定(bind)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31728984/