我想Rectangle
在一个Paint
事件中绘制一个using下面的代码:
e.Graphics.DrawRectangle(Pens.Red, x1, y1, width1, height1);
如何使用C#将矩形的宽度/高度数据绑定到ATextBox
中Form
?我想根据TextBox
输入立即更改绘制矩形的大小。
要解决该问题,请考虑以下几点:
Rectangle
是一个struct
,您不能将其用于数据绑定,因为在设置数据绑定时,您的结构将按Binding
值传递给对象,并且所有更改都将在它的另一个实例上进行。您需要一个类来保存数据绑定的属性。
为了能够刷新图形,您应该在Paint
图形表面出现事件时放置图形逻辑。然后,当您需要刷新图形时,请调用Invalidate
图形表面的方法。
您可以在更改文本后立即重绘矩形,而无需使用数据绑定。在这种情况下,只要Invalidate
在TextChanged
发生事件时调用绘制表面的方法TextBox
并解析输入的值,然后在Paint
事件中使用它绘制矩形就足够了。
例子
在此示例中,我使用aForm
作为绘图表面并在中定义Width1
和Height1
属性,Form
并将TextBox
控件绑定到这些属性。我调用this.Invalidate()
属性的setter来刷新窗体上的绘画:
public partial class Form1 : BaseForm
{
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
}
int x1, y1, width1, height1;
public int Width1
{
get { return width1; }
set { width1 = value; this.Invalidate(); }
}
public int Height1
{
get { return height1; }
set { height1 = value; this.Invalidate(); }
}
private void Form1_Load(object sender, EventArgs e)
{
x1 = 10; y1 = 10; Width1 = 100; Height1 = 100;
this.width1TextBox.DataBindings.Add("Text", this, "Width1", true,
DataSourceUpdateMode.OnPropertyChanged);
this.height1TextBox.DataBindings.Add("Text", this, "Height1", true,
DataSourceUpdateMode.OnPropertyChanged);
this.Paint += ProductListForm_Paint;
}
void ProductListForm_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(Pens.Red, x1, y1, Width1, Height1);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句