c# - Custom UI Binding objects to controls -
i creating own ui binding system, ties controls associated objects. better using series of if-statements? if add new controls serve new track items, not want update series of if statements every time.
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);
you could:
create
dictionary<type, type>
contains track types , corresponding control types:private static readonly dictionary<type, type> controltypes = new dictionary<type, type> { { typeof(shottrack), typeof(shottrackcontrol) }, ... };
to corresponding control:
control = activator.createinstance(controltypes[track.gettype()]);
create
dictionary<type, func<control>>
contains track types , corresponding control creators:private static readonly dictionary<type, func<control>> controltypes = new dictionary<type, func<control>> { { typeof(shottrack), () => new shottrackcontrol() }, ... };
to create new corresponding control:
control = controltypes[track.gettype()]();
define custom attribute stores corresponding control type:
[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 { ... }
to create new corresponding control:
object[] attrs = track.gettype().getcustomattributes(typeof(trackcontrolattribute), true); if (attrs.length != 0); control = activator.createinstance(((trackcontrolattribute)attrs[0]).controltype);
edit
bug fixed in 3rd option.
Comments
Post a Comment