在C#中,使用WinForms或WPF的Calendar控件時,可以通過自定義渲染器來改變日歷的顯示樣式。以下是兩種方法的詳細說明:
WinForms:
MonthCalendar
的自定義類。CreateCalendarControl()
和OnPaint()
方法。using
語句創建一個Graphics
對象,并使用Font
、Brush
等屬性設置自定義樣式。base.OnPaint()
方法完成日歷的繪制。以下是一個簡單的WinForms示例:
using System;
using System.Drawing;
using System.Windows.Forms;
public class CustomCalendar : MonthCalendar
{
public CustomCalendar()
{
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.UpdateStyles();
}
protected override void CreateCalendarControl()
{
base.CreateCalendarControl();
}
protected override void OnPaint(PaintEventArgs e)
{
using (Graphics g = e.Graphics)
{
// 設置字體和顏色
g.setFont(new Font("Arial", 12));
g.setColor(Color.Blue);
// 繪制日歷背景
g.FillRectangle(Brushes.LightGray, this.ClientRectangle);
// 繪制日期
for (int i = 0; i < this.Calendar.DaysInMonth; i++)
{
string dateText = this.Calendar.DateToString("dd");
int x = this.Calendar.GetCellPosition(this.Calendar.ActiveDate).X + (i % 7) * 24;
int y = this.Calendar.GetCellPosition(this.Calendar.ActiveDate).Y + (i / 7) * 28;
g.DrawString(dateText, this.Font, Brushes.Black, new Point(x, y));
}
}
base.OnPaint(e);
}
}
WPF:
CalendarControl
的自定義類。OnRender()
方法。using
語句創建一個Graphics
對象,并使用Font
、Brush
等屬性設置自定義樣式。base.OnRender()
方法完成日歷的繪制。以下是一個簡單的WPF示例:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
public class CustomCalendar : CalendarControl
{
public CustomCalendar()
{
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.UpdateStyles();
}
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
using (Graphics g = dc.CreateGraphics())
{
// 設置字體和顏色
g.setFont(new FontFamily("Arial"), 12);
g.setColor(Colors.Blue);
// 繪制日歷背景
g.FillRectangle(Brushes.LightGray, this.ActualWidth, this.ActualHeight);
// 繪制日期
for (int i = 0; i < this.Calendar.DaysInMonth; i++)
{
string dateText = this.Calendar.DateToString("dd");
int x = this.Calendar.GetCellPosition(this.Calendar.ActiveDate).X + (i % 7) * 24;
int y = this.Calendar.GetCellPosition(this.Calendar.ActiveDate).Y + (i / 7) * 28;
dc.DrawString(dateText, this.FontFamily, Brushes.Black, new Point(x, y));
}
}
}
}