Search code examples
c#wpfdatepickerstylesuielement

To align the Datepicker button and calender of Datepicker dynamically through code behind


My requirement is to align the DatePicker button and calender to the extreme right in the DatePicker control (only through code behind). I am creating a DatePicker control which is dynamically generated if the data type is date.

Here's the present code:

if (type.ToLower() == "date")
{
  control = new DatePicker();

  (control as DatePicker).Name = name;
  (control as DatePicker).FontSize = 24;
  (control as DatePicker).FontWeight = FontWeights.Light;
  (control as DatePicker).MinWidth = 450;
  (control as DatePicker).HorizontalContentAlignment = HorizontalAlignment.Left;
  (control as DatePicker).VerticalAlignment = VerticalAlignment.Center;
}

Just wanted to know, What extra i should write to keep the DatePicker button at the right such that the calender also should open at the right i.e to the bottom of the DatePicker button.

enter image description here


Solution

  • Don't set the HorizontalContentAlignment property of Left. If you avoid doing this, the calendar button will end up to in the right edge of the TextBox.

    If you then want the calendar to show up under the button, you could handle the Loaded event of the DatePicker and set the PlacementTarget property of the Popup in the template:

    (control as DatePicker).FontSize = 24;
    (control as DatePicker).FontWeight = FontWeights.Light;
    (control as DatePicker).MinWidth = 450;
    (control as DatePicker).VerticalAlignment = VerticalAlignment.Center;
    (control as DatePicker).Loaded += (ss, ee) =>
    {
        DatePicker dp = (DatePicker)ss;
        System.Windows.Controls.Primitives.Popup popup = dp.Template.FindName("PART_Popup", dp) as System.Windows.Controls.Primitives.Popup;
        Button button = dp.Template.FindName("PART_Button", dp) as Button;
        if (popup != null && button != null)
            popup.PlacementTarget = button;
    };