我正在Windows窗体中使用C#创建一个UserControl
。这是我的第一个.NET UserControl
,但是过去我在Delphi中创建了许多自定义组件,因此它并不是一个完全陌生的概念。
我的新控件是时间轴,类似于在视频编辑软件中看到的那些,您可以在其中将视频和音频放置在各个频道上。
我的控件还可以包含多个通道。我创建了一个用作基本时间轴的控件,并创建了另一个控件,将其添加到时间轴后成为Channel。
我已经创建了Channel对象的集合作为时间轴的属性,在设计模式下,它为我提供了一个集合编辑器,以便我可以添加,修改和删除Channels。我已经创建了Channel对象Serializeable
,并且我创建的Channels集合以放置时间轴的形式保留。
我想做的是,当我退出集合编辑器时,时间轴将更新为显示Channel对象。目前,它们存在于时间轴中,但未在时间轴中显示。 显然,必须将它们添加到“时间轴”对象的“控件”集合中,但是我不知所措,无法确定应该在哪里进行此操作。是否有某种事件表明收藏集已更改,以便我可以去添加或删除显示的时间轴中的频道?
这是我的时间轴控件代码:
using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.ComponentModel.Design;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace CMSTimeline
{
[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
public partial class CMSTimeline : UserControl
{
// The collection of Channels
private Collection<TimelineChannel> channels = new Collection<TimelineChannel>();
public CMSTimeline()
{
InitializeComponent();
}
// The property that exposes the collection of channels to the object inspector
[Category("Data")]
[Description("The Timeline channels")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Collection<TimelineChannel> Channels
{
get { return channels; }
set { channels = value; }
}
}
class CMSTimelineDesigner : ControlDesigner
{
public override void Initialize(IComponent component)
{
base.Initialize(component);
CMSTimeline uc = component as CMSTimeline;
}
}
}
这是Channel对象代码。
using System;
using System.Windows.Forms;
namespace CMSTimeline
{
[Serializable]
public partial class TimelineChannel : UserControl
{
public TimelineChannel()
{
InitializeComponent();
UICaption.Text = "Channel";
}
public TimelineChannel(string aCaption)
{
InitializeComponent();
UICaption.Text = aCaption;
}
public string Caption
{
get
{
return UICaption.Text;
}
set
{
UICaption.Text = value;
}
}
}
}
其他一切都很好。我的时间轴控件显示在“工具箱”中,可以将其拖放到表单上。
当我选择时间轴时,将显示其属性,包括Channels属性,该属性按预期显示为Collection。 按下[...]按钮将打开一个默认的集合编辑器(稍后可能会更改),并且我可以根据需要添加和删除通道。 关闭编辑器时,通道存在(我可以在窗体的Designer.cs文件中看到分钟),但是我希望它们出现在时间轴对象中。
那么我应该如何将它们添加到时间轴的控件中?
答案 0 :(得分:1)
使用Collection<TimelineChannel>
代替ObservableCollection<TimeLineChannel>
并向其中添加处理程序
myObservable.CollectionChanged += (sender, e) =>
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (TimeLineChannel c in e.NewItems)
{
TimeLine.Controls.Add(c);
}
}
};