DataGridTemplateColumn with DatePicker requires three clicks to edit the date
Asked Answered
S

2

5

I have a DataGridTemplateColumn. Inside its CellEditingTemplate, I put a DatePicker control. Now if I want to edit the date, I have to click three times to let DatePicker begin editing. Can someone let me know how I can get DatePicker into edit mode with only two clicks? Also, if DataGridTemplateColumn get focused, keyboard typing doesn't put DatePicker into edit mode as well. It would be nice if it can be fixed as well.

Stanleystanly answered 3/3, 2011 at 3:9 Comment(1)
Can you show the xaml? It would help us reproduce it and help you solve it.Aoudad
P
9

You have to override the PrepareCellForEdit in DataGridTemplateColumn as follows:

public class DataGridDateColumn:DataGridTemplateColumn
{
    protected override object PrepareCellForEdit(FrameworkElement editingElement,
                                                 RoutedEventArgs editingEventArgs)
    {
        editingElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
        return base.PrepareCellForEdit(editingElement, editingEventArgs);
    } 
}

XAML

<Custom:DataGrid x:Name="dgData" SelectionUnit="Cell" AutoGenerateColumns="False" CanUserAddRows="False">
    <Custom:DataGrid.Columns>
        <Custom:DataGridTextColumn Binding="{Binding Subject}" Header="Subject" Width="*"/>
        <Custom:DataGridTextColumn Binding="{Binding RaisedBy}" Header="Raised By" Width="100"/>

        <DatePickerDGWPF:DataGridDateColumn Header="Raised On" Width="250">
            <DatePickerDGWPF:DataGridDateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding RaisedOn}" />
                </DataTemplate>
            </DatePickerDGWPF:DataGridDateColumn.CellTemplate>
            <DatePickerDGWPF:DataGridDateColumn.CellEditingTemplate>
                <DataTemplate>
                    <Custom:DatePicker SelectedDate="{Binding RaisedOn}"/>       
                </DataTemplate>
            </DatePickerDGWPF:DataGridDateColumn.CellEditingTemplate>
        </DatePickerDGWPF:DataGridDateColumn>
    </Custom:DataGrid.Columns>
</Custom:DataGrid>
Polyclitus answered 3/3, 2011 at 4:41 Comment(0)
H
3

An easier solution would be to surround the datepicker with a grid and setting FocusManager on the DatePicker….

DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
       <Grid FocusManager.FocusedElement="{Binding ElementName=dPicker}">
           <DatePicker x:Name="dPicker"
                       SelectedDate="{Binding HistoryDate, Mode=TwoWay}"/>
       </Grid>
     </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
Heikeheil answered 20/9, 2018 at 9:52 Comment(1)
Works great, tyPneumodynamics

© 2022 - 2024 — McMap. All rights reserved.