Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent WPF Binding Exception: Cannot find source for binding with reference 'RelativeSource FindAncestor.....' reduces performance

I wrote the Style:

<Style x:Key="ProductItemContainerStyle"
           TargetType="{x:Type ListBoxItem}"
           BasedOn="{StaticResource ProductItemContainerBaseStyle}">
        <Setter Property="IsSelected"
                Value="{Binding Path=IsExpanded, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Expander}}, Mode=OneWayToSource}" />
    </Style>

It is relevant only when applying grouping for the ListBox that holds this ListBoxItem. However, most of the time it is not in grouping and this causes for dozens, hundreds and thousands of binding exception (depends on how many items are in the list). Binding Exception are known reason for performance problems. This binding should expand the Expander when code behind selects a ListBoxItem and IsSelected is changed to true. As you can see the binding is Mode=OneWayToSource.

Is there a way to prevent these binding exceptions?

like image 638
Mr.B Avatar asked Nov 27 '25 12:11

Mr.B


1 Answers

It is relevant only when applying grouping for the ListBox that holds this ListBoxItem ...

Then apply it only then, i.e. use a different style when you are indeed grouping or set the IsSelected property in a trigger that determines whether you are currently in a "grouped" stage.

If you hard-code the Setter into the default Style, then XAML processor will of course always try to resolve the binding. The only way to tell it not to is to remove the binding from the XAML.

Is there a way to prevent these binding exceptions?

The only way to do this is to either remove the failing binding. You can turn off the tracings under Tools->Options->WPF Trace Settings->Data Binding but this won't prevent the excpetions from being actually thrown when the XAML processor tries to resolve the bindings.

like image 66
mm8 Avatar answered Nov 30 '25 02:11

mm8