首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果内容不是null,则未使用的ListBoxItem会导致绑定错误

如果内容不是null,则未使用的ListBoxItem会导致绑定错误
EN

Stack Overflow用户
提问于 2015-07-30 16:14:20
回答 1查看 734关注 0票数 2

我注意到了ListBoxItem的这种奇怪之处,即使您实际上没有对您创建的ListBoxItem做任何事情,如果它的内容不是null,它将导致2个绑定错误。请注意,我没有创建任何绑定,并且我已经发布了重现这些错误所需的所有代码。

代码语言:javascript
复制
ListBoxItem li = new ListBoxItem();

代码语言:javascript
复制
ListBox lb = new ListBox();
ListBoxItem li = new ListBoxItem();
li.Content = "Something";
lb.Items.Add(li);

不会造成任何错误,但是

代码语言:javascript
复制
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')

有谁能说出这种行为的原因吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-30 16:33:54

这是因为ListBoxItem的默认样式包含一个带有RelativeSourceBinding,用于获取ListBoxItem对齐的包含ItemsControlHorizontal/Vertical ContentAlignment

就像这样:

代码语言:javascript
复制
<Style TargetType="ListBoxItem">
    <Setter Property="HorizontalAlignment" Value="{Binding HorizontalContentAlignment RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
</Style>

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31728984

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档