1
votes

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:

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

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:

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

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

2

2 Answers

0
votes

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.