gpt4 book ai didi

c# - 自定义 UI 绑定(bind)对象到控件

转载 作者:太空宇宙 更新时间:2023-11-03 10:46:49 25 4
gpt4 key购买 nike

我正在创建自己的 UI 绑定(bind)系统,它将控件绑定(bind)到它们的关联对象。有什么比使用一系列 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);

最佳答案

你可以:

  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);

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

关于c# - 自定义 UI 绑定(bind)对象到控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23064426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com