当我稍后将此 UserControl 拖到我的 form1 设计器时,我希望能够键入例如 PaintDrawingControl1。并且在具有所有属性的点之后还有属性字体和文本不是那些已经存在但是我需要在代码中而不是字体和 label1.Text 这样用户可以输入任何文本到 drawstring 和任何类型的字体。 我的意思是在这一行:PaintDrawingControl.font =.... or PaintDrawingControl.text = "draw this text"
整个想法是让用户控件在其上拉绳,这样它就不会闪烁。如果我在 form1 绘制事件中绘制字符串,则文本将在使用计时器时闪烁。
e.Graphics.DrawString(label1.Text,
font, Brushes.Black, 10, 10);
替换 label1.Text 并用全局变量替换变量字体,以便用户可以在 form1 设计器中拖动控件后将其设置为。 因此,在 form1 代码中,我将能够执行以下操作:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DateCounter
{
public partial class PaintDrawingControl : UserControl
{
public PaintDrawingControl()
{
InitializeComponent();
}
private void PaintDrawingControl_Load(object sender, EventArgs e)
{
}
private void PaintDrawingControl_Paint(object sender, PaintEventArgs e)
{
if (DesignMode) return;
e.Graphics.DrawString(label1.Text,
font, Brushes.Black, 10, 10);
}
}
}
最佳答案
这是我到目前为止所做的:
在用户控件端:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DateCounter
{
public partial class PaintDrawingControl : UserControl
{
public static string texttodraw;
public static Font font;
public PaintDrawingControl()
{
InitializeComponent();
}
private void PaintDrawingControl_Load(object sender, EventArgs e)
{
}
private void PaintDrawingControl_Paint(object sender, PaintEventArgs e)
{
if (DesignMode) return;
e.Graphics.DrawString(texttodraw,
font, Brushes.Black, 10, 10);
}
}
}
添加了两个全局公共(public)静态变量,一个用于绘制文本,一个用于字体。
在 form1 端,我将其更改为与计时器一起使用:
private void CounterToDate()
{
endTime = new DateTime(2016, 10, 21, 0, 0, 0);
Timer t = new Timer();
t.Interval = 500;
t.Tick += new EventHandler(t_Tick);
TimeSpan ts = endTime.Subtract(DateTime.Now);
PaintDrawingControl.texttodraw = ts.ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds'");
paintDrawingControl1.Invalidate();
t.Start();
}
void t_Tick(object sender, EventArgs e)
{
TimeSpan ts = endTime.Subtract(DateTime.Now);
PaintDrawingControl.texttodraw = ts.ToString("d' Days 'h' Hours 'm' Minutes 's' Seconds'");
paintDrawingControl1.Invalidate();
}
到目前为止,我没有看到任何闪烁。 到目前为止,一切正常。
如果我可以称之为问题的话,唯一的问题是在 form1 中我使用:
PaintDrawingControl 用于设置 texttodraw 和字体变量,我想使用 paintDrawingControl1,所以我想知道如何做到这一点只是为了学习如何将 paintDrawingControl1 与 texttodraw 和字体变量一起使用。
关于c# - 如何向 UserControl 添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37089119/