skjagini
skjagini

Reputation: 3217

Validating DatePicker value in WPF DataGrid using CellEditEnding Event

I am using WPF DataGrid's CellEditEnding event to validate data and perform other calculations. I have TextBoxes and DatePickers as DataGridTemplateColumns.

Here is how I invoking the event handler

    private void OnCellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
        if (e.EditAction == DataGridEditAction.Cancel) return;

        DataGridCellEditEndingCommandParameter p = new DataGridCellEditEndingCommandParameter();
        if (e.Column != null)
        {
            p.BindingPropertyName = e.Column.SortMemberPath;
            if (e.Column.Header != null)
                p.ColumnHeaderName = e.Column.Header.ToString();
        }

        TextBox t = e.EditingElement as TextBox;
        if (t != null) 
            p.EndingElementValue = t.Text;
        //else if (e.EditingElement as DatePicker) 

        if (e.Row != null) p.RowItem = e.Row.Item;

        p.EventArgs = e;
        p.Sender = sender as DataGrid;

        CommandParameter = p;
        ExecuteCommand();
    }

I am converting the EditingElement as TextBox to read the value entered by the user, doing the same for DatePicker though results in null when DatePicker is edited.

<DataGridTemplateColumn x:Name="fxFwd"  Header="Value Date" Width="70" SortMemberPath = "fwFwdDate" CanUsersort = "True">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path= fxFwdDate, 
            ConverterCulture={x:Static gl:CultureInfo.CurrentCulture}, 
            StringFormat=\{0:d\}}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <DatePicker SelectedDate="{Binding Path=fxFwdDate,
                ConverterCulture={x:Static gl:CultureInfo.CurrentCulture}, Mode=TwoWay,
                ValidatesOnExceptions=true, NotifyOnValidationError=true}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

When I inspected the EditingElement after changing the value of DatePicker, it is being received as ContentPresenter instead of DatePicker.

Thanks in advance

Upvotes: 1

Views: 3293

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81253

Set x:Name on your DatePicker control -

<DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
        <DatePicker x:Name="datePicker" />
    </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>

And you can fetch the DatePicker control in code-behind like this -

ContentPresenter contentPresenter = e.EditingElement as ContentPresenter;
DataTemplate editingTemplate = contentPresenter.ContentTemplate;
DatePicker dp = editingTemplate.FindName("datePicker", contentPresenter)
                            as DatePicker ;

Upvotes: 3

Related Questions