删除父级时如何避免绑定错误



我正在做一个WPF项目,我正在创建一些样式,其中之一是DataGridCell样式,它运行良好。

我的问题是:当用户删除任何行时,VisualStudio的"输出"窗口中都会显示许多错误

这就是错误:

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

所以,我想错误是因为当DataGridCellDataGrid中删除时,绑定找不到Parent,但是,我该怎么做才能避免这些错误??我的意思是,我如何才能建立绑定的条件

我的XAML样式代码如下:

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

希望有人能帮我,提前谢谢。

我也遇到过这种问题,设置TargetNullValue和FallbackValue在大多数情况下都可以消除这些绑定错误。

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

一般来说,我也尽量减少RelativeSource的使用,尽可能使用DataContext

最新更新