Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid Binding Error when parent is removed

I am working on a WPF project, and I am creating some styles, one of them is the DataGridCell style, it works fine.

My problem is that: When the user delete any row, many errors are shown in the Visual Studio's Output window.

This is the error:

System.Windows.Data Warning: 4 : Cannot find source for binding with reference 
 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', 
 AncestorLevel='1''.
 BindingExpression:Path=CanUserAddRows; DataItem=null; target element is 'DataGridCell' 
 (Name=''); target property is 'NoTarget' (type 'Object')

So, I guess the error is because when the DataGridCell is removed from the DataGrid, the binding does not find the the Parent, but, What can I do to avoid getting these errors?? I mean, how can I establish a condition for the binding??

My XAML Style code is as following:

<DataGrid Margin="6,25,6,35" x:Name="dataGrid">            
        <DataGrid.CellStyle>
            <Style TargetType="{x:Type DataGridCell}">
                <Style.Triggers>
                    <MultiDataTrigger>
                        <MultiDataTrigger.Conditions>
                            <Condition Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=CanUserAddRows}" Value="False" />
                            <Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsSelected}" Value="True" />
                        </MultiDataTrigger.Conditions>
                        <Setter Property="Background" Value="#A4A4A4"/>
                    </MultiDataTrigger>
. . . . . 

Hope someone can help me, thanks in advance.

like image 765
Dante Avatar asked Nov 04 '22 20:11

Dante


1 Answers

I have also faced this kind of problems and setting TargetNullValue and FallbackValue gets rid of these binding errors most of the time.

<MultiDataTrigger.Conditions> 
   <Condition Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
                         AncestorType= {x:Type DataGrid}}, Path=CanUserAddRows, 
                         TargetNullValue=False, FallbackValue=False}" Value="False" /> 
   <Condition Binding="{Binding RelativeSource={RelativeSource Self}, 
                         Path=IsSelected, TargetNullValue=False, 
                         FallbackValue=False}" Value="True" /> 
</MultiDataTrigger.Conditions> 

In general, I also try to minimize the use of RelativeSource as much as possible, use DataContext wherever possible.

like image 140
akjoshi Avatar answered Nov 15 '22 07:11

akjoshi