![](/img/trans.png)
[英]How do I return all items in a collection that possess an interface property of a specific type?
[英]How do I “Invalidate” after adding items to a collection property?
我正在创建一个自定义控件,我在其中创建“列表”类型的属性
Sections是一个公共类,有4个属性。
控件中的代码如下所示:
public partial class genericGauge : Control
{
public genericGauge()
{
InitializeComponent();
}
// Stripped out code not needed for this issue question.
private List<Sections> indicators = new List<Sections>();
public List<Sections> Indicators
{
get
{
return indicators;
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// Stripped out code not needed for this issue question.
}
}
章节类如下:
public class Sections
{
private string header = "Section1";
public string Header
{
get {return header;}
set
{
header = value;
}
}
private float startvalue = 0.0f;
public float StartValue
{
get { return startvalue; }
set
{
startvalue = value;
}
}
private float sweepvalue = 0.0f;
public float SweepValue
{
get { return sweepvalue; }
set
{
sweepvalue = value;
}
}
private Color sectioncolor = new Color();
public Color SectionColor
{
get {return sectioncolor;}
set
{
sectioncolor = value;
}
}
}
一切似乎都运行良好,除了当我在设计时使用属性浏览器typeeditor向集合添加项目时,控件不会重新绘制以反映添加到集合中的内容。
当我点击我的测试表格上的控件外面时,它被重新绘制。 通常使用简单属性我会使用Invalidate,但这似乎不可能在这里。 我还尝试使用除List <>之外的其他集合类型,其中允许有一个set访问器,但仍然不会调用Invalidate。 我认为这意味着从未调用过SET。
我知道如何使用可扩展属性,但我没有找到如何使用集合进行此更新。
我希望有人可以帮助我。 提前致谢。
不使用类List,而是使用ObservableCollection类,并使用它来在列表中添加或删除新节时收到通知。
private ObservableCollection<Sections> indicators = new ObservableCollection<Sections>();
public IList<Sections> Indicators
{
get
{
return indicators;
}
}
public genericGauge()
{
InitializeComponent();
this.indicators.CollectionChanged += this.IndicatorsCollectionChanged;
}
private void IndicatorsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// possibly inspect the NotifyCollectionChangedEventArgs to see if it's a change that should cause a redraw.
// or not.
this.Invalidate();
}
完全按原样使用您的示例时,属性窗口中的“指标”属性无法进行编辑。 所以我做了一些改动。
我添加了一个新类:
// Added this class to deal with the Sections class
public class SectionObservable : ObservableCollection<Sections>
{
// Added a few methods here for creating a designtime collection if I need to.
}
然后我按你的建议做了改变
public genericGauge()
{
InitializeComponent();
this.indicators.CollectionChanged += this.IndicatorsCollectionChanged; // your suggestion
}
并使这个属性改为:
private SectionObservable indicators = new SectionObservable(); // using the SectionObservable class instead
public SectionObservable Indicators // using the SectionObservable class instead
{
get
{
return indicators;
}
}
private void IndicatorsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) // your suggestion
{
this.Invalidate();
}
而现在作为一种魅力。 非常感谢你。 我很欣赏能够快速获得帮助。 我很喜欢这个论坛。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.