Hello. I have a DataGrid of the following form:

<DataGrid ItemsSource="{Binding Plavkas}" Grid.Row="1" CanUserAddRows="False" CanUserDeleteRows="False" SelectionMode="Single" SelectedItem="{Binding CurrentPlavka}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Плавка" Binding="{Binding plavka1}" /> <DataGridComboBoxColumn x:Name="catMetalColumn" Header="Категория" DisplayMemberPath="category" SelectedItemBinding="{Binding catMetal1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> <DataGridTextColumn x:Name="smenaColumn" Binding="{Binding smena}" Header="Смена"/> <DataGridTemplateColumn x:Name="dataPrig" Header="Дата приготовление."> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <DatePicker Height="19" FontSize="11" Padding="5,0,0,0" Margin="5,0,5,0" SelectedDate="{Binding dataPrig, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Loaded="ComboBox_Loaded" SelectedDateChanged="DatePicker_SelectedDateChanged" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> 

How can I prevent editing the records if the dataPrig cell contains yesterday's date (that is, the difference between the dataPrig and today's date is 1 day)?

    1 answer 1

    I usually use styles for this.

    First we need a converter that will say whether the day has passed or not:

     public class MyConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return (DateTime.Now - datePrig).TotalDays >= 1 ? false : true; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } 

    We register our converter into resources, for example, windows:

     <Window.Resources> <local:MyConverter x:Key="myConverter"/> </Window.Resources> 

    Now we describe the style:

     <DataGrid.Resources> <Style TargetType="DataGridRow"> <Setter Property="IsEnabled" Value="{Binding Path=datePrig, Converter={StaticResource myConverter}}"/> </Style> </DataGrid.Resources> 

    Now, if a day or more has passed, the DataGridRow.IsEnabled property will be set to false , and the row will turn out to be uneditable.

    • And how can I make it ReadOnly? And even the record can not be selected, and I have events written for it there. - zerpico
    • @Pandacun, well, then, probably, only through the DataGrid.BeginningEdit event: private void DataGrid_BeginningEdit (object sender, DataGridBeginningEditEventArgs e) {if (...) {e.Cancel = true; // Deny editing}} The class instance bound to a row is in e.Row.Item . - Donil