c# - 如果内容不为空,未使用的 ListBoxItem 会导致绑定(bind)错误

标签 c# wpf

我注意到 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 的默认样式包含一个 BindingRelativeSource 来获取 Horizo​​ntal/Vertical ListBoxItem 的对齐方式的包含 ItemsControlContentAlignment

像这样:

<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/

相关文章:

c# - 解析CSV的正则表达式

c# - 为什么我在调用 RoleEnvironment.GetConfigurationSettingValue ("MYKEY"时收到 SEHException?

c# - 可扩展的 WPF 应用程序 - MEF、MAF 或简单加载?

c# - 我如何在 XAML 中将弹出窗口居中放置在我的窗口中?

c# - 在集合 MVVM 中过滤集合

wpf - 命名空间 "clr-namespace:Project.ViewModels"中不存在名称 ViewModel

c# - RDL 是否可以有可选参数或强制默认值为空

c# - 如何优化每个不同值具有多个键的字典?

c# - 当我在运行时添加控件时,以编程方式绑定(bind)不起作用

c# - 如何限制 rdlc 报告表中显示的行数?