如何在加载时调试wpf relativesource抛出错误?

时间:2021-12-05 14:14:38

I'm working with a WPF dialog window that contains a ListBox. The list box can display both an 'icon' and 'list' view. To accomplish this, we used ListBoxItem styles that are dynamically applied to the ListBox, as well as a pair of corresponding ItemsPanelTemplates. As is, it displays beautifully. However, when loading this dialog we get a few dozen binding errors, such as the following:

我正在使用包含ListBox的WPF对话框窗口。列表框可以显示“图标”和“列表”视图。为此,我们使用了动态应用于ListBox的ListBoxItem样式,以及一对相应的ItemsPanelTemplates。它的显示效果很好。但是,加载此对话框时,我们会收到几十个绑定错误,例如:

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')

System.Windows.Data错误:4:无法找到绑定源,引用'RelativeSource FindAncestor,AncestorType ='System.Windows.Controls.ItemsControl',AncestorLevel ='1''。 BindingExpression:路径= VerticalContentAlignment;的DataItem = NULL; target元素是'ListBoxItem'(Name =''); target属性是'VerticalContentAlignment'(类型'VerticalAlignment')

Our theory is that the styles and templates are loading before the ListBox, and failing to find the properties they are bound to using code such as:

我们的理论是样式和模板在ListBox之前加载,并且无法使用以下代码找到它们绑定的属性:

<Setter Property="VerticalContentAlignment" Value="{Binding 
        Path=VerticalContentAlignment, RelativeSource={RelativeSource 
        AncestorType={x:Type ItemsControl}}}"/> 

This seems to happen one or more times before the ListBox is initialized and the styles and templates are applied. After the dialog finishes initializing, the errors stop.

在ListBox初始化并应用样式和模板之前,这似乎发生了一次或多次。对话框完成初始化后,错误停止。

Has anyone encountered this before? Can anyone suggest a solution we may have overlooked?

有没有人遇到过这个?任何人都可以建议我们可能忽略的解决方案吗?

2 个解决方案

#1


Looks like this was covered here:

看起来这里有这样的内容:

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/db050ce6-d084-41ad-9a31-c01831687683

Supposed to be a "known" issue.

被认为是一个“已知”的问题。

#2


I found a fix here:

我在这里找到了一个修复:

http://blog.jtango.net/2009/05/08/using-a-grid-as-the-itemspanel-for-a-listbox-in-wpf-binding-errors/

You set the style using ItemContainerStyle on the ListBox.

您可以使用ListBox上的ItemContainerStyle设置样式。

#1


Looks like this was covered here:

看起来这里有这样的内容:

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/db050ce6-d084-41ad-9a31-c01831687683

Supposed to be a "known" issue.

被认为是一个“已知”的问题。

#2


I found a fix here:

我在这里找到了一个修复:

http://blog.jtango.net/2009/05/08/using-a-grid-as-the-itemspanel-for-a-listbox-in-wpf-binding-errors/

You set the style using ItemContainerStyle on the ListBox.

您可以使用ListBox上的ItemContainerStyle设置样式。