WPF DatePicker Date-Validation after Enter key pressed

108 Views Asked by At

I have set an InputBinding in a WPF application, along with a DatePicker and a TextBox.

When I press the Enter key while the focus is not on the DatePicker, my KeyBinding Event is triggered.

When the focus is on the DatePicker, the validation from the DatePicker is executed. After the validation, neither the KeyDown nor the KeyBinding command is executed.

I suspect that the DatePicker-TextBox sets 'Handled' to true.

Is there any way that I can access the validation function from the DatePicker?

 <Window.InputBindings>
     <KeyBinding Key="Enter" Command="{Binding EnterCommand}" />
 </Window.InputBindings>

 <Grid>
     <StackPanel>
         <DatePicker
             KeyDown="DatePicker_KeyDown"
             PreviewKeyDown="DatePicker_PreviewKeyDown" />

         <TextBox Height="20" />
     </StackPanel>
 </Grid>

WPF datagrid with datepicker in cell blocks the enter key

With this CustomDatePicker I can change Handled to false.

But it would be better if the first Enter press starts the validation and sets 'Handled' to true, and a second Enter press would start the KeyBinding event.

Is there any way to achieve this?

1

There are 1 best solutions below

1
On

If you want to invoke the EnterCommand whenever the Enter key is pressed regardless of which control that currently has the focus and how this control is implemented, you should handle the PreviewKeyDown event instead of using a KeyBinding:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        PreviewKeyDown += (s, e) =>
        {
            dynamic viewModel = DataContext; //..or cast to your type
            viewModel.EnterCommand.Execute(null);
        };

        ...
        }
    }
}

This is exactly as MVVM compliant as your current solution of using a KeyBinding but it works better (depending on your requirements).