0
votes

I am binding a DataTable to Datagrid. Number of columns and rows in datatable is determined at runtime. But number of rows displayed in datagrid is fixed to 36.

So if sometimes datatable have <36 rows, empty rows are displayed to maintain height of datagrid. Reason behind doing this is that I am printing the Grid containing datagrid and I dont want to mess up Height and Width of print template.

    <DataGrid x:Name="TestPointsDataGrid" ItemsSource="{Binding TestPointsTable,Mode=TwoWay}" HorizontalScrollBarVisibility="Disabled" 
CanUserResizeColumns="False" CanUserResizeRows="False" MouseRightButtonUp="DataGrid_MouseRightButtonUp"   
                                      CanUserAddRows="False" >

To disable first and last columns I did below style triggers :

    <Style TargetType="{x:Type DataGridCell}">
       <Style.Triggers>
          <Trigger Property="IsMouseOver" Value="True">
             <Setter Property="Background" Value="Aqua"></Setter>
          </Trigger>
          <DataTrigger Value="Type" Binding="{Binding Path=Column.Header, RelativeSource={RelativeSource Self}}">
              <Setter Property="IsEnabled"  Value="false" />
              <Setter Property="FontWeight" Value="DemiBold"/>
           </DataTrigger>
           <DataTrigger Value="B or A" Binding="{Binding Path=Column.Header, RelativeSource={RelativeSource Self}}">
               <Setter Property="IsEnabled"  Value="false" />
               <Setter Property="FontWeight" Value="DemiBold"/>
               <Setter Property="Foreground" Value="Black"/>
            </DataTrigger>
       </Style.Triggers>
   </Style>

Example : enter image description here

enter image description here

As shown in above images, numbers of columns are unknown. First column and last column is always fixed in my case. i.e. "Type" and "B or A" respectively. I was able to set IsEnabled = false for these columns.

If there is something in first column, let user edit that row except first and last column. How do I set those empty rows' IsEnabled property to false ? Or just any workaround to prevent user from typing anything in those rows except not displaying those rows.

1

1 Answers

1
votes

The easiest thing for you to do is to add a BeginningEdit event handler and cancel the edit if the row that the user is trying to edit is empty...

<DataGrid x:Name="dataGrid" ItemsSource="{Binding PartCollection}" AutoGenerateColumns="True" BeginningEdit="dataGrid_BeginningEdit">

    private void dataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
    {
        if((e.Row.Item as Part).Manufacturer == "XYZ")
        {
            e.Cancel = true;
        }
    }