Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComboBoxItem continues to throw binding error despite style

I have a combobox that I am populating via a CollectionViewSource. The items are build though a datatemplate for the incoming item type (in this case a ProjectViewModel). This is in WPF in .NET 4.0.

In my window.resources, I have specified the following:

    <Style TargetType="{x:Type ComboBoxItem}">
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
    </Style>

Despite this style, I am still getting the following errors:

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 'ComboBoxItem' (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 'ComboBoxItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

I have specified the Horizontal and Vertical ContentAlignment on the ComboBox element as well, to no avail. This is not a terrible problem as the items appear correctly. however when debugging, I do get about a 10 second delay when closing the window while it outputs about 4000 error messages to the output window (which I need open to catch legitimate binding errors.

I may not be reading the error correctly. Why can it not find a valid source for the binding? As far as I know, the way I am using the ComboBox and CollectionViewSource is in line with their intent.

like image 917
CodeWarrior Avatar asked Feb 25 '13 15:02

CodeWarrior


1 Answers

I'd thought I'd solved this problem in my own program, but found that it kept popping up intermittently. Finally managed to track down the source of the issue.

If you're using a combobox backed by an ICollectionView, and you stack two or more collectionView.Refresh() calls on the event queue (ie: calling refresh twice because of two different cleanup operations, for example), that will cause it to generate the binding error spam on each element of the combobox for each additional Refresh() call made. This binding error will only occur after you have opened the combobox at least once.

Rewriting it so that you only call Refresh() once for a given event will prevent the binding error from popping up.

like image 189
dsmith Avatar answered Nov 15 '22 05:11

dsmith