单元格中带有datepicker的WPF数据网格阻止了回车键

时间:2016-08-21 16:35:09

标签: c# wpf datagrid datepicker textblock

我在Datagrid中有一个Datepicker / Textblock。我可以选择,并输入日期,但是,输入键或单击事件不会将日期输入数据网格。如果我在数据网格外部单击,它将接受日期值。我很困惑发生了什么。有什么想法会发生这种情况吗?解决方案是什么?

这里的代码似乎很简单。

<DataGrid x:Name="dgTestingDates"  ItemsSource="{Binding TestingDates}"  CanUserAddRows="True" AutoGenerateColumns="False" HorizontalAlignment="Left" HorizontalContentAlignment="Stretch" ColumnWidth="*" Margin="21,300,0,0" VerticalAlignment="Top" Height="165" Width="245" >
        <DataGrid.Columns>
            <DataGridTemplateColumn >
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Time,UpdateSourceTrigger=LostFocus}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
                        <DatePicker SelectedDate="{Binding Path=Time,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

1 个答案:

答案 0 :(得分:0)

这解决了我的问题。...

public class CustomDatePicker : DatePicker
{
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        if (Template != null)
        {
            var box = (TextBox)Template.FindName("PART_TextBox", this);
            box.AddHandler(KeyDownEvent, new KeyEventHandler(OnTextBoxKeyDown), true);
        }
    }

    private void OnTextBoxKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            // The DatePicker set this as handled, which breaks the DataGrid commit model.
            e.Handled = false;
        }
    }
}