我正在创建一个自定义控件,我在其中创建“List”类型的属性
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.
}
}
Sections Class如下:
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&lt;&gt;允许有一个set访问器,但仍然不会调用Invalidate。我认为这意味着从未调用过SET。
我知道如何使用可扩展属性,但我没有找到如何使用集合进行此更新。
我希望有人可以帮助我。 提前谢谢。
答案 0 :(得分:3)
不使用类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();
}
答案 1 :(得分:0)
完全按原样使用您的示例时,属性窗口中的“指标”属性无法进行编辑。所以我做了一些改动。
我添加了一个新课程:
// 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();
}
现在作为一种魅力。 非常感谢你。我很欣赏能够快速获得帮助。我很喜欢这个论坛。