简体   繁体   中英

WPF datagrid IsReadOnly exception

I have a datagrid where i have added a Checkbox column. I want the entire datagrid to be IsReadOnly except the Checkbox column. I have tried:

  <DataGrid x:Name="DataGridView_Customer_Information" HorizontalAlignment="Left" Margin="10,200,0,0" VerticalAlignment="Top" Height="410" Width="697" CanUserAddRows="False" IsReadOnly="True" >
        <DataGrid.Columns>
            <DataGridCheckBoxColumn x:Name="CheckBoxSelectRow" IsReadOnly="False"/>
        </DataGrid.Columns>
    </DataGrid>

But i can imagine that <DataGridCheckBoxColumn x:Name="CheckBoxSelectRow" IsReadOnly="False"/> is overruled by the previous statement. Since its only one column that needs to be able to allow edit (allow to checkmark the checkbox) is it possible to make an expection in the IsReadOnly?

Thanks in advanced

You have two options. Both assumes, that DataGrid.AutoGenerateColumns is False .

  1. Remove IsReadOnly="True" from DataGrid element and set IsReadOnly for each column: False for DataGridCheckBoxColumn , True for the rest of columns.

  2. Leave IsReadOnly="True" for DataGrid as is, and instead of DataGridCheckBoxColumn add DataGridTemplateColumn with CheckBox inside template:

     <DataGrid IsReadOnly="True" AutoGenerateColumns="False" ItemsSource="{Binding Guests}"> <DataGrid.Columns> <DataGridTemplateColumn Header="Is invited"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox IsChecked="{Binding IsInvited}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="False"/> </DataGrid.Columns> </DataGrid> 

The second approach has another benefit. Default behavior of DataGridCheckBoxColumn is weird - to change check mark you need to select cell first, which is not convenient. CheckBox inside DataGridTemplateColumn accepts user input without selecting cell, and this looks natural.

You can set each other column IsReadOnly to false .

Update

Or you can add into DataGrid.Resources styles for other columns

<DataGrid.Resources>
    <Style TargetType="{x:Type DataGridTextColumn}">
        <Setter Property="IsReadOnly" Value="True" />
    </Style>
</DataGrid.Resources>

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