我使用枚举来填充我的ListView项目。
填充后我希望在onclick后得到特定的usercontrol, 使用Enum标记或其他内容。
我使用Description
指定项目名称。但
我还想为每个Enum绑定他的UserControl。
我想这样做(伪代码):
onClick(object sender, Args....){
ItemXY foo = sender as ItemXY
this.UserControl = foo.getUserControl();
...
}
我的枚举:
public enum UserControlsEnum
{
[Description("Cash")]
Cash = 0,
[Description("History")]
Velocity = 1,
[Description("Statistik")]
Statistik = 2,
[Description("Information")]
Info = 3,
[Description("Administration")]
Admin = 4,
[Description("About")]
About = 5
}
我的问题是:
是否有像Description这样的标签将特定视图的名称设置为字符串,甚至更好地直接设置特定视图?
喜欢:
[Description("Cash")]
-->[Tag("ItemView.xaml")]
Cash = 0,
答案 0 :(得分:4)
这应该有效:
public sealed class ViewTagAttribute : Attribute
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="viewType"></param>
public ViewTagAttribute(System.Type viewType)
{
this.type = viewType;
}
/// <summary>
/// Create an instance of the associated view
/// </summary>
/// <returns></returns>
public static View CreateViewInstanceForEnumValue<T>(T enumValue)
{
var attributes = typeof(T).GetField(enumValue.ToString()).GetCustomAttributes(true);
var viewAttr = (from a in attributes where a is ViewTagAttribute select (ViewTagAttribute)a).FirstOrDefault();
if (viewAttr != null)
return System.Activator.CreateInstance(viewAttr.type) as View;
return null;
}
/// <summary>
/// Associated view type
/// </summary>
private readonly System.Type type;
}
然后,您可以使用ViewTag属性为每个枚举成员设置控件,例如:
public enum UserControlsEnum
{
[Description("Cash")]
[ViewTag(typeof(View1))]
Cash = 0,
[Description("History")]
[ViewTag(typeof(View2))]
Velocity = 1,
[Description("Statistik")]
[ViewTag(typeof(View3))]
Statistik = 2,
[Description("Information")]
[ViewTag(typeof(View1))]
Info = 3,
[Description("Administration")]
[ViewTag(typeof(View1))]
Admin = 4,
[Description("About")]
[ViewTag(typeof(View1))]
About = 5
}
然后您可以使用以下内容创建视图:
this.UserControl = (UserControl)ViewTagAttribute.CreateViewInstanceForEnumValue(foo);