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

3

我注意到了一个关于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:Path = HorizontalContentAlignment; DataItem = null; target element is 'ListBoxItem' (Name = ''); target property is 'HorizontalContentAlignment' (type = 'HorizontalAlignment')

System.Windows.Data错误:4:找不到引用'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')

有人能告诉我是什么原因导致了这种行为吗?


你的绑定XAML在哪里? - Glen Thomas
1
不要使用XAML和绑定。 - FINDarkside
1个回答

3
ListBoxItem 的默认样式包含一个 Binding,使用 RelativeSource 获取包含 ItemsControlHorizontal/Vertical ContentAlignment 以用于 ListBoxItem 的对齐。
<Style TargetType="ListBoxItem">
    <Setter Property="HorizontalAlignment" Value="{Binding HorizontalContentAlignment RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
</Style>

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


其实这并不是同样的情况。首先,你缺少内容,而且它不应该被添加到任何无法使用 XAML 实现的东西中。 - FINDarkside
我误解了问题。我会再看一遍。 - Glen Thomas
但如果我不添加内容它为什么能工作呢?如果我不将其添加到任何东西中,为什么会出现错误?垃圾收集器不应该只是删除它吗? - FINDarkside
当您不设置Content属性时,ControlTemplate不会应用,因此绑定不会创建并且不会尝试解析值。当您创建控件的实例时,即使您尚未将其附加到可视树中,WPF也会应用模板。 - Glen Thomas
这是因为 ListBoxItem 的模板在添加到 ListBox 后尚未呈现。您方法中的每个语句都不会立即执行,而是由 Dispatcher 将工作添加到队列中。 - Glen Thomas
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接