How can I make the DatePicker control update the view model without losing focus?
I'd like to be able to run this sample, type 12/9/11 for the date, click the close button for the window and have the Debug.Assert pass. If I tab to the text box before closing the window it works fine.
<Window x:Class="DatePickerTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Closing="MainWindow_OnClosing">
<StackPanel>
<DatePicker Name="TheDate" SelectedDate="{Binding Path=SelectedDate}" />
<TextBox/>
</StackPanel>
</Window>
using System;
using System.ComponentModel;
using System.Diagnostics;
namespace DatePickerTest
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
private void MainWindow_OnClosing(object sender, CancelEventArgs e)
{
var dataContext = DataContext as ViewModel;
Debug.Assert(dataContext.SelectedDate == new DateTime(2011, 12, 9));
}
}
public class ViewModel
{
public DateTime SelectedDate { get; set; }
}
}