![](/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.