fau*_*ity 3 .net c# numericupdown winforms
我对 C# 很陌生,有一个问题。我已经能够通过将 FlatStyle 更改为“Flat”来更改按钮的边框颜色等。使用NumericUpDown,我无法更改 FlatStyle。我希望仍然能够使用向上和向下箭头,因此仅使用其他东西来覆盖边缘是行不通的。这是我在代码中所做的事情的简化版本:
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace bordertest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
BackColor = Color.Black;
numericUpDown1.BackColor = Color.Red;
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以从 派生NumericUpDown、添加BorderColor属性、覆盖OnPaint并根据边框颜色绘制边框。
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
public class MyNumericUpDown : NumericUpDown
{
private Color borderColor = Color.Blue;
[DefaultValue(typeof(Color), "0,0,255")]
public Color BorderColor
{
get { return borderColor; }
set
{
if (borderColor != value)
{
borderColor = value;
Invalidate();
}
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (BorderStyle != BorderStyle.None)
{
using (var pen = new Pen(BorderColor, 1))
e.Graphics.DrawRectangle(pen,
ClientRectangle.Left, ClientRectangle.Top,
ClientRectangle.Width - 1, ClientRectangle.Height - 1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:作为旁注,此控件会引发绘制事件,如果出于任何原因有人想要在不继承的情况下实现相同的行为,他们可以处理 Paint 事件并绘制边框;然而,作为一种通用解决方案和可重用解决方案,派生控件更有意义。
private void numericUpDown_Paint(object sender, PaintEventArgs e)
{
var c = (NumericUpDown)sender;
ControlPaint.DrawBorder(e.Graphics, c.ClientRectangle,
Color.Red, ButtonBorderStyle.Solid);
var r = new Rectangle(1, 1, c.Width - 2, c.Height - 2);
e.Graphics.SetClip(r);
}
Run Code Online (Sandbox Code Playgroud)
平面数字向上向下
BorderColor我创建了一个支持和的 FlatNumericUpDown ButtonHighlightColor。您可以下载或克隆它:
| 归档时间: |
|
| 查看次数: |
2487 次 |
| 最近记录: |