简体   繁体   中英

Is it possible to center the text of DateTimePicker?

In my Windows Form Application written in C#, I have a DateTimePicker control. I want to center the text part of the control, but is it possible? My current one has its text at the left, giving a lot of space on the right side.

在此处输入图片说明

I tried

myDateTimePicker.TextAlign = ContentAlignment.MiddleCenter;

but it gave the error:

'System.Windows.Forms.DateTimePicker' does not contain a definition for 'TextAlign' and no extension method 'TextAlign' accepting a first argument of type 'System.Windows.Forms.DateTimePicker' could be found (are you missing a using directive or an assembly reference?)

I could not find any property that seemed to work, and I could not find the solution anywhere on the Internet either. Is this not possible at all?

You can always override the OnPaint handler by subclassing DateTimePicker :

public class CenteredDateTimePicker : DateTimePicker
{
    public CenteredDateTimePicker()
    {
        SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle, new StringFormat
        {
            Alignment = StringAlignment.Center,
            LineAlignment = StringAlignment.Center
        });
    }
}

However, the scrollbar is not drawn here, so you might have to improvise somehow...

Unfortunately, you can't find the definition of DateTimePicker.OnPaint on Reference Source .

一个简单但不是很优雅的解决方案是在您的自定义格式属性中添加空格,但是,如果您的 datetimepicker 大小是动态的,它将不会相应地调整。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM