通过code behind动态对齐Datepicker的Datepicker按钮和日历

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

我的要求是将DatePicker按钮和日历对齐到DatePicker控件中的最右端(仅通过代码隐藏)。我正在创建一个 DatePicker 控件,如果数据类型是日期,它会动态生成。

这是目前的代码:

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;
}

只是想知道,为了让 DatePicker 按钮保持在右侧,我还应该写些什么 日历也应该在右侧打开,即 DatePicker 按钮的底部。

不要设置 LeftHorizontalContentAlignment 属性。如果您避免这样做,日历按钮将最终位于 TextBox.

的右边缘

如果您希望日历显示在按钮下方,您可以处理 DatePickerLoaded 事件并设置 PlacementTarget 属性 Popup 模板中:

(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;
};