Wpf – Disabled row on Datagrid WPF getting selected when clicked with the Right Mouse Button

datagridright-clickwpfxaml

I got some problems in Datagrid WPF

I have a datagrid, and I want to set the IsEnabled property of a single row to false whenever the user assign a value to the binding item of the datagrid itemSource

So I made it by datagrid Style triggers:

               <DataGrid AutoGenerateColumns="False" Margin="9,35,0,6" Name="dataGrid2" ItemsSource="{Binding}" SelectionChanged="dataGrid2_SelectionChanged" IsReadOnly="True" SelectionMode="Single">
                    <DataGrid.RowStyle>


                        <Style TargetType="{x:Type DataGridRow}">
                            <Style.Setters>
                                <Setter Property="IsEnabled" Value="False" />
                            </Style.Setters>
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding Path=Coluna}" Value="{x:Null}">
                                    <Setter Property="IsEnabled" Value="True"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>



                    </DataGrid.RowStyle>
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="Campo" Binding="{Binding Path=Campo}" Width="1.4*" CanUserSort="False" />
                        <DataGridTextColumn Header="Coluna/Constante" Binding="{Binding Path=Coluna}" CanUserSort="False" Width="*" />
                    </DataGrid.Columns>
                </DataGrid>

Working fine, it disables the entire row when a value is assigned to the "Coluna" field of that row (different of null)

The problem is: I still can click and select the disabled row using the right mouse button… Does the "IsEnabled" property only blocks the left mouse button click on datagrid rows?? Do I need to set another property to disable the right mouse button click on that row?

Thank you!

Best Answer

This is a known bug of the DataGrid and it's reported on Connect here: DatagridRow gets selected on right click even if the datagrid is disabled. Looks like this will be fixed in WPF 4.5.

To workaround it you can bind IsHitTestVisible to IsEnabled

<DataGrid ...>
    <DataGrid.RowStyle>
        <Style TargetType="{x:Type DataGridRow}">
            <Setter Property="IsEnabled" Value="False" />
            <Setter Property="IsHitTestVisible"
                    Value="{Binding RelativeSource={RelativeSource Self},
                                    Path=IsEnabled}"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Coluna}" Value="{x:Null}">
                    <Setter Property="IsEnabled" Value="True"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
    <!-- ... -->
</DataGrid>
Related Topic