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

本文关键字:错误 绑定 ListBoxItem 如果 未使用 | 更新日期: 2023-09-27 18:05:30

我已经注意到这个奇怪的事情与ListBoxItem,即使你实际上不做任何事情与ListBoxItem你创建它会导致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。数据错误:4:找不到绑定引用'RelativeSource FindAncestor, AncestorType='System.Windows.Controls '的源。ItemsControl",AncestorLevel ="1"。BindingExpression:路径= HorizontalContentAlignment;DataItem =零;目标元素是'ListBoxItem' (Name= ");目标属性是'HorizontalContentAlignment'(类型为'HorizontalAlignment')

System.Windows。数据错误:4:找不到绑定引用'RelativeSource FindAncestor, AncestorType='System.Windows.Controls '的源。ItemsControl",AncestorLevel ="1"。BindingExpression:路径= VerticalContentAlignment;DataItem =零;目标元素是'ListBoxItem' (Name= ");目标属性为'VerticalContentAlignment'(类型为'VerticalAlignment')

谁能告诉我是什么导致了这种行为?

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

这是因为ListBoxItem的默认样式包含BindingRelativeSource,以获得Horizontal/Vertical ContentAlignment的包含ItemsControlListBoxItem的对齐。

像这样:

<Style TargetType="ListBoxItem">
    <Setter Property="HorizontalAlignment" Value="{Binding HorizontalContentAlignment RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
</Style>

您创建的ListBoxItem不包含在ItemsControl中,因此RelativeSource Binding无法找到该类型的祖先。