自定义UI将对象绑定到控件

本文关键字:控件 绑定 对象 UI 自定义 | 更新日期: 2023-09-27 17:58:27

我正在创建自己的UI绑定系统,该系统将控件绑定到关联的对象。还有什么比使用一系列if语句更好的呢?如果我添加新的控件来提供新的跟踪项,我不想每次都更新这一系列If语句。

TimelineTrackControl control;
Type objectType = track.GetType();
if (objectType == typeof(ShotTrack))
{
    control = new ShotTrackControl();
}
else if (objectType == typeof(AudioTrack))
{
    control = new AudioTrackControl();
}
else if (objectType == typeof(GlobalItemTrack))
{
    control = new GlobalItemTrackControl();
}
else
{
    control = new TimelineTrackControl();
}
control.TargetTrack = track;
timelineTrackMap.Add(track, control);

自定义UI将对象绑定到控件

您可以:

  1. 创建一个包含轨道类型和相应控制类型的Dictionary<Type, Type>

    private static readonly Dictionary<Type, Type> ControlTypes = new Dictionary<Type, Type>
    {
        { typeof(ShotTrack), typeof(ShotTrackControl) },
        ...
    };
    

    要获得相应的控制:

    control = Activator.CreateInstance(ControlTypes[track.GetType()]);
    
  2. 创建一个包含轨道类型和相应控件创建者的Dictionary<Type, Func<Control>>

    private static readonly Dictionary<Type, Func<Control>> ControlTypes = new Dictionary<Type, Func<Control>>
    {
        { typeof(ShotTrack), () => new ShotTrackControl() },
        ...
    };
    

    创建新的对应控件:

    control = ControlTypes[track.GetType()]();
    
  3. 定义一个自定义属性,用于存储相应的控制类型:

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    public class TrackControlAttribute : Attribute
    {
        public readonly Type ControlType;
        public TrackControlAttribute(Type controlType)
        {
            ControlType = controlType;
        }
    }
    [TrackControl(typeof(ShotTrackControl))]
    public class ShotTrack
    {
        ...
    }
    

    创建新的对应控件:

    object[] attrs = track.GetType().GetCustomAttributes(typeof(TrackControlAttribute), true);
    if (attrs.Length != 0);
        control = Activator.CreateInstance(((TrackControlAttribute)attrs[0]).ControlType);
    

    编辑
    在第三个选项中修复了错误。

在这种情况下,可以使用反射http://msdn.microsoft.com/en-us/library/vstudio/d133hta4像这样:

Activator.CreateInstance(null, track.GetType().toString() + "Control");