手动输入日期时,DatePickerSelectedDateChanged事件发生两次

时间:2015-12-01 10:43:49

标签: wpf events datepicker

我有一个管理SelectedDateChanged事件的DatePicker:

<DatePicker Name="myDatePicker" SelectedDateChanged="myDatePicker_SelectedDateChanged" />

如果我选择日历的日期,则会触发一次SelectedDateChanged事件。如果我手动更改日期,则会触发SelectedDateChanged事件两次。

我发现其他人在谈论同一个问题并通过首次触发事件时设置标志来解决它,并测试标志值。

我想找到一种不同方法来解决我的问题,而不使用旗帜。

2 个答案:

答案 0 :(得分:0)

第一次触发DatePicker SelectedDate,第二次触发Calendar SelectedDate ......所以这不是错误,这是奇怪的逻辑。

答案 1 :(得分:0)

我设法做了我想做的事。

加载表单时,我将GotFocus和LostFocus事件添加到DatePicker TextBox(使用Template.FindName方法)。我还在DatePicker上添加了CalendarOpened和CalendarClosed事件 它不是很优雅,如果你认为有更好的方法,可以自由评论,我是WPF的初学者......

public partial class MainWindow : Window
{
    private TextBox txtDtPicker;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        txtDtPicker = (TextBox)myDatePicker.Template.FindName("PART_TextBox", myDatePicker);

        myDatePicker.CalendarOpened += new RoutedEventHandler(myDatePicker_CalendarOpened);
        myDatePicker.CalendarClosed += new RoutedEventHandler(myDatePicker_CalendarClosed);

        txtDtPicker.GotFocus += new RoutedEventHandler(txtDtPicker_GotFocus);
        txtDtPicker.LostFocus += new RoutedEventHandler(txtDtPicker_LostFocus);
    }

    private void txtDtPicker_GotFocus(object sender, RoutedEventArgs e)
    {
        myDatePicker.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(myDatePicker_SelectedDateChanged);
    }

    private void txtDtPicker_LostFocus(object sender, RoutedEventArgs e)
    {
        myDatePicker.SelectedDateChanged -= new EventHandler<SelectionChangedEventArgs>(myDatePicker_SelectedDateChanged);
    }

    private void myDatePicker_CalendarOpened(object sender, RoutedEventArgs e)
    {
        myDatePicker.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(myDatePicker_SelectedDateChanged);
    }

    private void myDatePicker_CalendarClosed(object sender, RoutedEventArgs e)
    {
        myDatePicker.SelectedDateChanged -= new EventHandler<SelectionChangedEventArgs>(myDatePicker_SelectedDateChanged);

        // When calendar is closed after a date selection, unfocus and focus again txtDtPicker. If not done, SelectedDateChanged event will not fire if date is changed manually just after changed was done with calendar
        myDatePicker.Focus();
        txtDtPicker.Focus();
    }

    int iNbTimesEventOccurs = 0;

    private void myDatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
    {
        // Remove event to prevent it to happen twice
        myDatePicker.SelectedDateChanged -= new EventHandler<SelectionChangedEventArgs>(myDatePicker_SelectedDateChanged);

        // Just to control event is not fired several times
        iNbTimesEventOccurs++;
        textBlock1.Text = "Nb times event occurs: " + iNbTimesEventOccurs;
    }
}