带有DatePicker的DataGridTemplateColumn需要三次单击才能编辑日期

时间:2011-03-03 03:09:08

标签: wpf wpfdatagrid datagridtemplatecolumn

我有DataGridTemplateColumn。在CellEditingTemplate内,我放了一个DatePicker控件。现在,如果我想编辑日期,我必须单击三次才能让DatePicker开始编辑。有人可以告诉我如何只需点击两次即可DatePicker进入编辑模式吗?此外,如果DataGridTemplateColumn聚焦,键盘输入也不会将DatePicker置于编辑模式。如果它也可以修复它会很好。

2 个答案:

答案 0 :(得分:9)

您必须覆盖PrepareCellForEdit中的DataGridTemplateColumn,如下所示:

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>

答案 1 :(得分:0)

更简单的解决方案是用网格包围日期选择器,并在DatePicker上设置FocusManager…。

DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
       <Grid FocusManager.FocusedElement="{Binding ElementName=dPicker}">
           <DatePicker x:Name="dPicker"
                       SelectedDate="{Binding HistoryDate, Mode=TwoWay}"/>
       </Grid>
     </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>