Disable selecting in WPF DataGrid

96,323

Solution 1

There is a trick for this. You can handle SelectionChanged event of the DataGrid(say dgGrid) and in the handler write:

dgGrid.UnselectAll();

It will unselect all selected row and result will be "No row selected".

Solution 2

The clean way would be, to just override the styles of the row and the cell

<DataGrid.Resources>
    <ResourceDictionary>
        <Style x:Key="{x:Type DataGridCell}" TargetType="{x:Type DataGridCell}">
            <Setter Property="Background" Value="{x:Null}" />
            <Setter Property="BorderBrush" Value="{x:Null}" />
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="{x:Null}" />
                    <Setter Property="BorderBrush" Value="{x:Null}" />
                </Trigger>
            </Style.Triggers>
        </Style>
        <Style TargetType="{x:Type DataGridRow}">
            <Setter Property="Background" Value="{x:Null}" />
            <Setter Property="BorderBrush" Value="{x:Null}" />
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="{x:Null}" />
                    <Setter Property="BorderBrush" Value="{x:Null}" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ResourceDictionary>
</DataGrid.Resources>

Solution 3

To completely disable selection of rows in a DataGrid, you could do the following:

<DataGrid>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsHitTestVisible" Value="False"/>
        </Style>
    </DataGrid.RowStyle>
    <!--Other DataGrid items-->
</DataGrid>

This could be considered more favorable than setting <Setter Property="IsEnabled" Value="False"/> due to the fact that doing the aforementioned technique causes the style of the row to change. It also does not disable context menus from appearing when right-clicking.

Lastly: it is important to note that setting "IsHitTestVisible" to "False" disables all interaction with the rows, including editing.

However, if all you want to do is change the styling of the row when selected, please view the answers here.

Solution 4

Simply add IsHitTestVisible="False" to DataGrid definition.

Solution 5

All of the above are good ideas for easy hacks. However, they aren't doing exactly what is asked. The other answers are telling us how to unselect something selected by the user or hide the fact that something was selected by the user.

However, I understand why these answers are given. It is not easy to provide the real solution.

The real solution is to prevent selection in the first place, which it is not straightforward but it is doable with a few easy steps.

Answer 1. You have to copy the style in Expression Blend (or find a copy of the style somewhere). 2. Change a single ItemPresenter setting. It was enough for me to set IsHitTestVisible="False" on the ItemPresenter.

If you need more details, or an in-depth walk-thru for doing this, see my blog post:

How to disable row selection in a WPF DataGrid?

Share:
96,323
svick
Author by

svick

Updated on July 09, 2022

Comments

  • svick
    svick almost 2 years

    How can I disable selecting in a WPFTooklit's DataGrid? I tried modifying the solution that works for ListView (from WPF ListView turn off selection), but that doesn't work:

    <tk:DataGrid>
        <tk:DataGrid.ItemContainerStyle>
            <Style TargetType="{x:Type tk:DataGridRow}">
                <Setter Property="Focusable" Value="false"/>
            </Style>
        </tk:DataGrid.ItemContainerStyle>
        <tk:DataGrid.CellStyle>
            <Style TargetType="{x:Type tk:DataGridCell}">
                <Setter Property="Focusable" Value="false"/>
            </Style>
        </tk:DataGrid.CellStyle>
    </tk:DataGrid>
    
  • Mikhail Poda
    Mikhail Poda about 13 years
    Does not work: this works: stackoverflow.com/questions/3046988/…
  • viky
    viky about 13 years
    +1 Thats a right one :)...anyways mine is working fine in my case :)
  • Zero
    Zero almost 12 years
    That's not quite correct either - it stops clicks happening on the DataGridCells, which often is not desirable.
  • Rhyous
    Rhyous almost 12 years
    Agreed. One of these days I am going to have to find a solution that disables select but allows click.
  • OneWorld
    OneWorld over 11 years
    This disabled selection at all. I had to replace "{x:Null}" by "Transparent" to keep selection working. This is the way Mr. Snuggles recommended.
  • Sherlock
    Sherlock almost 11 years
    This method should be combined with setting the DataGrid SelectionMode property to "Single" ... otherwise you can select multiple cells before the event is fired.
  • edtheprogrammerguy
    edtheprogrammerguy almost 11 years
    This prevents the vertical scrollbar from responding to the mouse.
  • Norman Skinner
    Norman Skinner over 10 years
    Nikhil's version worked perfectly for me. I can edit cells directly in the DataGrid and the entire row stays unselected. Thanks Nikhil.
  • JiBéDoublevé
    JiBéDoublevé almost 10 years
    FYI, dont't forget to set <Setter Property="Foreground" Value="Black"/> in the trigger otherwise the text of the selection will be, by default, white.
  • Riegardt Steyn
    Riegardt Steyn over 9 years
    Works like a charm... and if you bind the value to an INPC property, then you can be selective about which rows are selectable :-)
  • Xcelled
    Xcelled over 9 years
    @JiBéDoublevé I just had to do this, however instead of using a hardcoded value, I put this in the DataGridCell's Triggers: <Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource Self}, Path=Foreground}"/>, which sets it to what it already is. Strangely, it seems explicitly setting a color on the column definition also removes the color change, without the need for a setter.
  • polfosol ఠ_ఠ
    polfosol ఠ_ఠ over 7 years
    This answer kinda saved my life!
  • JoshuaTheMiller
    JoshuaTheMiller over 7 years
    You should avoid interacting with view logic in the code behind/viewmodel
  • Slate
    Slate about 6 years
    Along with the vertical scrollbar issue, this also disables mouse clicking for child controls.
  • Beauty
    Beauty over 5 years
    If you want to keep settings of a default style (e. g. by Material Design), then you can add this to the style tags: BasedOn="{StaticResource {x:Type DataGridCell}}" and BasedOn="{StaticResource {x:Type DataGridRow}}" ... As result only the border is removed, not the whole default style.
  • Matt Gregory
    Matt Gregory over 5 years
    What do you do about all the controls still turning blue? The textblock backgrounds in each cell turn blue, and I have dropdowns and buttons in datatemplates that have a blue border when the row is selected.
  • FluffyKitten
    FluffyKitten over 3 years
    Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Also, please edit your answer to explain how it works and how it improves on the many other upvoted answers this question already has, so that it is useful to other users with similar issues.
  • Piano Telope
    Piano Telope over 3 years
    I don't think it would be a good idea to delete one of only two clear, succinct, and correct answers to the question. You don't need to touch the codebehind, you don't need styles, you don't need to mention alternate colours. All you need is a well-placed property.
  • FluffyKitten
    FluffyKitten over 3 years
    If that's why you think this is a good answer, then add that information into your answer! Users may not know if this even works with so little code when the other answers are more comprehensive, so you need to tell them how it works and why they don't need the rest. This is why code-only answers are discouraged, as I explained... if users don't understand how or why your answer will work (especially when there are so many other upvoted ones), then it's not very helpful to them, or worse - they might even think its wrong.
  • Piano Telope
    Piano Telope over 3 years
    I'm amazed at the high standards you hold my answer to while having such low expectations of readers. I think they'll manage to copy and paste the property into their data grid and see that it works. Half the stuff you want me to bloat the answer with is offtopic: it doesn't answer the question.
  • FluffyKitten
    FluffyKitten over 3 years
    That not how Stack Overflow works. It’s purpose is to act like an “encyclopaedia” for programming questions, and this answer was flagged by the community as low quality for lack of detail.
  • Piano Telope
    Piano Telope over 3 years
    We agree that answers should help the asker to solve their problem. This answer does so, We both want to help answer people's questions. I suggest we move on to the next person's question and leave this answer as at least good enough.
  • FluffyKitten
    FluffyKitten over 3 years
    As I said, this answer was flagged by the community, I’m just one of the reviewers, so it’s not me you need to convince.
  • Paul Palmpje
    Paul Palmpje about 3 years
    Old answer but I'd like to comment on this. My solution has Rows with a separate ViewModel. In order to totally disable the datagrid you can use DataGrid.Style and TargetType = "DataGrid". Because I need to control when selecting items is allowed I use a Value ="{Binding SomeProperty}" and then that property has to be on the DataContext. Gave me a binding error if the property was on the main DataContext when ussing a RowStyle setup.
  • Rye bread
    Rye bread almost 3 years
    This works, but prevents clicking any buttons.
  • JoshuaTheMiller
    JoshuaTheMiller almost 3 years
    @Rugbrød: "it is important to note that setting "IsHitTestVisible" to "False" disables all interaction with the rows, including editing." This includes clicking buttons.
  • Jonathan
    Jonathan about 2 years
    This will make the whole datagrid be grayed out, most likely now what people are after.