我一直在寻找解决方案,但我似乎无法找到一个,但我想这可能很简单。
我已经构建了一个带有属性的自定义控件类。 当我更改任何此类属性时,我的控件不会自动刷新(既不是在设计器中也不是以编程方式)。有没有办法强制使用Invalidate()方法?
我已经按照我发现的一些提示,但似乎没有任何工作。
这是一个代码示例来演示我正在经历的事情。
这是我的自定义类型。
[TypeConverter(typeof(ExpandableObjectConverter))]
public class TextComponent
{
public TextComponent()
{
Text= string.Empty;
Font = Control.DefaultFont;
ForeColor = Control.DefaultForeColor;
}
[NotifyParentProperty(true)]
public string Text { get; set; }
[NotifyParentProperty(true)]
public Font Font { get; set; }
[NotifyParentProperty(true)]
public Color ForeColor { get; set; }
}
这是我的自定义控件:
public partial class myControl : Control
{
private TextComponent tc = new TextComponent();
protected override void OnPaint(PaintEventArgs pe)
{
pe.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
GraphicsPath gp = new GraphicsPath();
Rectangle rect = new Rectangle(1, 1, DisplayRectangle.Width - 3, DisplayRectangle.Height - 3);
gp.AddRectangle(rect);
pe.Graphics.FillPath(new SolidBrush(Color.LightCoral), gp);
using (StringFormat sf = new StringFormat())
{
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
pe.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
pe.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
pe.Graphics.DrawString(tc.Text, tc.Font, new SolidBrush(tc.ForeColor), rect, sf);
}
base.OnPaint(pe);
}
[Description("The Text Component for the Control"), Category("Text"), NotifyParentPropertyAttribute(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public TextComponent TextComponent { get { return tc; } }
public myControl()
{
this.DoubleBuffered = true;
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.Selectable, true);
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new string Text { get { return string.Empty; } }
}
答案 0 :(得分:1)
尝试侦听PropertyChanged事件以使其工作。您必须将INotifyPropertyChanged接口添加到您的类并启动它:
[TypeConverter(typeof(ExpandableObjectConverter))]
public class TextComponent : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected void OnChanged(string propertyName) {
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private string text = string.Empty;
[NotifyParentProperty(true)]
public string Text {
get { return text; }
set {
text = value;
OnChanged("Text");
}
}
}
然后在您的控制类中,监听事件并使控件无效:
public myControl() {
this.DoubleBuffered = true;
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.Selectable, true);
this.TextComponent.PropertyChanged += TextComponent_PropertyChanged;
}
void TextComponent_PropertyChanged(object sender, PropertyChangedEventArgs e) {
this.Invalidate();
}