2008-10-13 45 views
11

En .NET (al menos en la versión 2008, y tal vez también en 2005), cambiar la propiedad BackColor de DateTimePicker no tiene ningún efecto en la apariencia. ¿Cómo cambio el color de fondo del área de texto, no del calendario desplegable?Cambiar el color de fondo de DateTimePicker en .NET

Editar: yo estaba hablando de formas de Windows, no es ASP.

Respuesta

14

Según MSDN:

Ajuste del BackColor tiene ningún efecto sobre la aparición de la DateTimePicker.

Necesita escribir un control personalizado que se extienda DateTimePicker. Reemplace la propiedad BackColor y el método WndProc.

Cuando cambie el BackColor, no olvide llamar al método myDTPicker.Invalidate(). Esto obligará al control a volver a dibujarse utilizando el nuevo color especificado.

const int WM_ERASEBKGND = 0x14; 
protected override void WndProc(ref System.Windows.Forms.Message m) 
{ 
    if(m.Msg == WM_ERASEBKGND) 
    { 
     using(var g = Graphics.FromHdc(m.WParam)) 
     { 
      using(var b = new SolidBrush(_backColor)) 
      { 
       g.FillRectangle(b, ClientRectangle); 
      } 
     } 
     return; 
    } 

    base.WndProc(ref m); 
} 
+0

Lo siento, tomó tanto tiempo para aceptar. Esperaba que hubiera otras soluciones que no implicaran conocer valores hexadecimales, entonces me olvidé de esto. –

+0

Gracias por esta publicación. Estoy dibujando un control DateTimePicker personalizado y esto me puso en la dirección correcta. –

+7

Intenté este cambio en Vista (con y sin estilos visuales) y no funciona. –

2

para el área de texto que tendría que hacerlo en el cuadro de texto real que va a agregar el extensor en
para C# que lo haría así:

<asp:TextBox runat="server" ID="txt" BackColor="Aqua" Text="Date"></asp:TextBox> 
+0

Siento que haya tardado tanto en llegar a este limitado. Pensé que ya había agregado este comentario. Estaba hablando de aplicaciones de Windows, no de aplicaciones ASP. –

3

No es una implementación libre derivado de DateTimePicker que le permite cambiar BackColor propiedad sobre el cambio.

Ver el sitio web CodeProject: DateTimePicker with working BackColor

+0

Esa es una versión completamente lobotomizada en la que solo se puede usar el menú desplegable del calendario para elegir realmente una fecha. – Nyerguds

1

Basado en this project (tal como fue anunciado anteriormente) Yo he reescrito una clase selector de fechas personalizado (en VB.NET) que permite personalizar el color de fondo, el TextColor y la pequeña imagen que aparece al lado del botón desplegable.

Eg.1:

enter image description here

Eg.2:

enter image description here

para que funcione simplemente crear una nueva clase en su proyecto con el siguiente código y reconstruir la Solución . Un nuevo control denominado MyDateTimePicker debería aparecer ahora en la lista de la caja de herramientas:

Public Class MyDateTimePicker 
    Inherits System.Windows.Forms.DateTimePicker 
    Private _disabled_back_color As Color 
    Private _image As Image 
    Private _text_color As Color = Color.Black 

    Public Sub New() 
     MyBase.New() 
     Me.SetStyle(ControlStyles.UserPaint, True) 
     _disabled_back_color = Color.FromKnownColor(KnownColor.Control) 
    End Sub 

    ''' <summary> 
    '''  Gets or sets the background color of the control 
    ''' </summary> 
    <Browsable(True)> 
    Public Overrides Property BackColor() As Color 
     Get 
      Return MyBase.BackColor 
     End Get 
     Set 
      MyBase.BackColor = Value 
     End Set 
    End Property 

    ''' <summary> 
    '''  Gets or sets the background color of the control when disabled 
    ''' </summary> 
    <Category("Appearance"), Description("The background color of the component when disabled")> 
    <Browsable(True)> 
    Public Property BackDisabledColor() As Color 
     Get 
      Return _disabled_back_color 
     End Get 
     Set 
      _disabled_back_color = Value 
     End Set 
    End Property 

    ''' <summary> 
    '''  Gets or sets the Image next to the dropdownbutton 
    ''' </summary> 
    <Category("Appearance"), 
    Description("Get or Set the small Image next to the dropdownbutton")> 
    Public Property Image() As Image 
     Get 
      Return _image 
     End Get 
     Set(ByVal Value As Image) 
      _image = Value 
      Invalidate() 
     End Set 
    End Property 

    ''' <summary> 
    '''  Gets or sets the text color when calendar is not visible 
    ''' </summary> 
    <Category("Appearance")> 
    Public Property TextColor As Color 
     Get 
      Return _text_color 
     End Get 
     Set(value As Color) 
      _text_color = value 
     End Set 
    End Property 


    Protected Overrides Sub OnPaint(e As System.Windows.Forms.PaintEventArgs) 
     Dim g As Graphics = Me.CreateGraphics() 
     g.TextRenderingHint = Drawing.Text.TextRenderingHint.ClearTypeGridFit 

     'Dropdownbutton rectangle 
     Dim ddb_rect As New Rectangle(ClientRectangle.Width - 17, 0, 17, ClientRectangle.Height) 
     'Background brush 
     Dim bb As Brush 

     Dim visual_state As ComboBoxState 

     'When enabled the brush is set to Backcolor, 
     'otherwise to color stored in _disabled_back_Color 
     If Me.Enabled Then 
      bb = New SolidBrush(Me.BackColor) 
      visual_state = ComboBoxState.Normal 
     Else 
      bb = New SolidBrush(Me._disabled_back_color) 
      visual_state = ComboBoxState.Disabled 
     End If 

     'Filling the background 
     g.FillRectangle(bb, 0, 0, ClientRectangle.Width, ClientRectangle.Height) 

     'Drawing the datetime text 
     g.DrawString(Me.Text, Me.Font, New SolidBrush(TextColor), 5, 2) 

     'Drawing icon 
     If Not _image Is Nothing Then 
      Dim im_rect As New Rectangle(ClientRectangle.Width - 40, 4, ClientRectangle.Height - 8, ClientRectangle.Height - 8) 
      g.DrawImage(_image, im_rect) 
     End If 

     'Drawing the dropdownbutton using ComboBoxRenderer 
     ComboBoxRenderer.DrawDropDownButton(g, ddb_rect, visual_state) 

     g.Dispose() 
     bb.Dispose() 
    End Sub 
End Class 

* Tenga en cuenta que esta clase se simplifica, por lo que tiene funcionabilidad

+0

Esto funciona, incluso en Windows 7. Pero cambia el aspecto de DatetimePicker debido a Combobox. Buena solución, sin embargo. – LuckyLuke82

Cuestiones relacionadas