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 ItemsPanelTemplate
s. 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?