Search code examples
.netwpfvisual-studiobindingwpfdatagrid

Binding warning when scrolling horizontally in datagrid


In my WPF application, when I scroll horizontally a DataGrid, Visual Studio 2010 Output print this warning:

System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='-0.29487179487171' BindingExpression:Path=CellsPanelHorizontalOffset; DataItem='DataGrid' (Name=''); target element is 'Button' (Name=''); target property is 'Width' (type 'Double')

I'm looking for datagrid template definition; the exception should be caused by the binding on "Button" object:

<Button
       Command="{x:Static DataGrid.SelectAllCommand}"
       Focusable="false"
       Style="{DynamicResource {ComponentResourceKey ResourceId=DataGridSelectAllButtonStyle, TypeInTargetAssembly={x:Type DataGrid}}}"
       Visibility="{Binding Path=HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.All}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
       Width="{Binding Path=CellsPanelHorizontalOffset, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />

Width property is Double, like the CellsPanelHorizontalOffset property in binding.

I can not understand what's wrong, can you help me? Thanks.


Solution

  • The reason for your error is clear from its description:

    Value produced by BindingExpression is not valid for target property.;
    Value='-0.29487179487171' ...
    target element is 'Button'; ...
    target property is 'Width'

    Therefore, the value that is data bound to the Button.Width is -0.29487179487171, but obviously, a Width cannot be negative. However, if you were to use a Converter there to never pass negative values, you'd simply be hiding the real problem, which is that the CellsPanelHorizontalOffset should never be negative in the first place.

    I can only assume that you have used some manual calculation in your customised DataGrid that is returning the wrong value from the DataGridCellsPanel. From the DataGrid Class page on MSDN:

    DataGridCellsPanel: Gets the horizontal offset for the DataGridCellsPanel.