Tuesday 7 May 2013

Wiring events to a Popup control in Silverlight

Last week I was doing some work on a Silverlight application and I was struggling with an event not firing for a calendar control inside a popup control and it turns out that the reason is very simple, I was wiring the event to the popup rather than the calendar control inside the popup.

This is the method I used to create the calendar within the popup. 

private void CreateCalendar()
{
    if (calendar == null)
    {
        calendar = new Calendar();
        calendar.SetValue(Grid.ColumnProperty, 10);
        calendar.SetValue(Grid.RowProperty, 0);
        calendar.SetValue(Grid.RowSpanProperty, 7);
        calendar.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
      
        var StartDateBinding = new System.Windows.Data.Binding();
        StartDateBinding.Path = new PropertyPath("StartDate");
        StartDateBinding.Mode = System.Windows.Data.BindingMode.TwoWay;
        StartDateBinding.ValidatesOnDataErrors = true;
        calendar.SetBinding(Calendar.SelectedDateProperty, StartDateBinding);

        var displayDateBinding = new System.Windows.Data.Binding();
        displayDateBinding.Path = new PropertyPath("CalendarStartsOn");
        calendar.SetBinding(Calendar.DisplayDateStartProperty, displayDateBinding);

        popup.DataContext = viewModel;

        popup.Child = calendar;            

        calendar.MouseLeave += (o, e) =>
        {
            popup.IsOpen = false;
            LayoutRoot.Children.Remove(popup);
        };
  
 calendar.SelectedDatesChanged += (o, e) =>
        {
     CreateAppointment();
            popup.IsOpen = false;
            LayoutRoot.Children.Remove(popup);
        };

    }

}

The calendar and popup objects are global objects of the MainPage partial class (i.e. they can be found in main.xaml.cs) and the CreateCalendar method gets called on the constructor, via the AddPopUp method, see below

The popup is closed when a date is selected, in which case we create an appointment, method not shown, for the user or when the mouse leaves the calendar.

private void AddPopUp()
{    
    CreateCalendar();
    LayoutRoot.Children.Remove(popup);
    LayoutRoot.Children.Add(popup);
    
    popup.VerticalOffset = 50;
    popup.HorizontalOffset = Application.Current.Host.Content.ActualWidth - 100;
    
    popup.IsOpen = true;
}

No comments:

Post a Comment