Dynamically adding SelectedDateChanged event to Calendar in WPF

Answered Dynamically adding SelectedDateChanged event to Calendar in WPF

  • Tuesday, February 28, 2012 8:28 PM
     
      Has Code

    I want my form to include a date picker.  So, upon clicking a button, a Calendar control is created and added.  This Calendar control (called cldrDateOfData) should have an event handler added which will fire when a date is selected in the Calendar.

    So, I assume the button's event will look something like

                Calendar cldrDateOfDate = new Calendar();
                cldrDateOfDate.Height = 170;
                cldrDateOfDate.HorizontalAlignment = HorizontalAlignment.Left;
                cldrDateOfDate.Margin = new Thickness(101, 31, 0, 0);
                cldrDateOfDate.Name = "cldrDateOfData";
                cldrDateOfDate.VerticalAlignment = VerticalAlignment.Top;
                cldrDateOfDate.Width = 180;
                cldrDateOfDate.DisplayMode = CalendarMode.Year;
                cldrDateOfDate.Visibility = System.Windows.Visibility.Visible;
                cldrDateOfDate.SelectedDatesChanged += new EventHandler<SelectionChangedEventArgs>(SelectDateOfData);

    but I'm not sure how the SelectDateOfData method should look.  How do I pull out the date that was selected from the cldrDateOfData control?

All Replies

  • Tuesday, February 28, 2012 8:48 PM
    Moderator
     
     Answered Has Code

    In Visual Studio, to complete an event handler, just type the "+=", then wait. intellisense will kick in and offer to create the event handler, just press Tab to create it.

    This is what it produces:

            public CalenderPage()
            {
                InitializeComponent();
    
                Calendar cldrDateOfDate = new Calendar();
                cldrDateOfDate.Height = 170;
                cldrDateOfDate.HorizontalAlignment = HorizontalAlignment.Left;
                cldrDateOfDate.Margin = new Thickness(101, 31, 0, 0);
                cldrDateOfDate.Name = "cldrDateOfData";
                cldrDateOfDate.VerticalAlignment = VerticalAlignment.Top;
                cldrDateOfDate.Width = 180;
                cldrDateOfDate.DisplayMode = CalendarMode.Year;
                cldrDateOfDate.Visibility = System.Windows.Visibility.Visible;
                cldrDateOfDate.SelectedDatesChanged += new EventHandler<SelectionChangedEventArgs>(cldrDateOfDate_SelectedDatesChanged);
            }
    
            void cldrDateOfDate_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
            {
               
            }

    You can find out more about the event args here: http://msdn.microsoft.com/en-us/library/system.windows.controls.selectionchangedeventargs.selectionchangedeventargs.aspx

    And I'm sure that should give you enough clues to find the rest of what you need.

    Good luck!
    Pete


    #PEJL

    • Marked As Answer by Newmanb1 Tuesday, February 28, 2012 9:54 PM
    •