简体   繁体   中英

C# WPF Datagrid how to disable selection cell on specific column

Brand new here on SO and brand new with WPF datagrid.

I have been searching in all opened threads concerning Datagrid but I can't find any answers to my problem.

I'm trying to display datas into a datagrid. So far so good. I'm trying to let user select cells in datagrid. So far so good. I want to disable selection cells on specifics columns.

See image in link.

How can disable selection cells on Torque columns or Average column and let the user select only cells on columns Mes1 Mes2 Mes3

datagrid的示例

If you want to prevent cells in certain columns from being selected, you could use a DataGridCell style that sets the IsHitTestVisible property of these cells to true :

<DataGrid x:Name="dataGrid1">
    <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridCell}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Column.Header, RelativeSource={RelativeSource Self}}" Value="Torque">
                    <Setter Property="IsHitTestVisible" Value="False"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Column.Header, RelativeSource={RelativeSource Self}}" Value="Average">
                    <Setter Property="IsHitTestVisible" Value="False"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Resources>
</DataGrid>

I am just playing with the code. But when I click on a cell in for example Column Mes 1, and then use keyboard to navigate, cells of column Torque and Average can be focused :-(

I guess you will have to set the IsEnabled property to false then:

<DataTrigger Binding="{Binding Column.Header, RelativeSource={RelativeSource Self}}" Value="Torque">
    <Setter Property="IsHitTestVisible" Value="False"/>
    <Setter Property="IsTabStop" Value="False"/>
    <Setter Property="IsEnabled" Value="False"/>
</DataTrigger>

One can use CellTemplate , In the example below one of the columns cells will be an image:

<DataGrid ItemsSource="{Binding Customers}" AutoGenerateColumns="False" >
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
        <DataGridTemplateColumn Header="Image" Width="SizeToCells" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Image Source="{Binding Image}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM