为每个列表生成按钮

时间:2014-08-13 06:57:07

标签: c# list

我在静态类中有一系列列表(用作全局类)

public static class globalClass
{
    public static List<classA> aList = new List<classA>();
    public static List<classB> bList = new List<classB>();
    public static List<classC> cList = new List<classC>();
}

我想为每个列表生成一个xaml按钮,并被告知反射是一个坏主意。这就是我使用反射处理它的方式。

//get FieldInfo for globalClass
TypeInfo typeInfo = IntrospectionExtensions.GetTypeInfo(typeof(globalClass));
IEnumerable<FieldInfo> FieldInfoList = typeInfo.DeclaredFields;

foreach (FieldInfo f in FieldInfoList)
{
    //Only look at lists
    if(f.FieldType.ToString().StartsWith("System.Collections.Generic.List`1")){
        StackPanel s = new StackPanel();
        s.Orientation = Orientation.Horizontal;

        TextBlock textBlock = new TextBlock();
        textBlock.FontSize = 45;
        textBlock.Text = f.Name.ToString();

        Button addButton = new Button();
        addButton.Click += delegate(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(addObjectToLibraryPage), f);
        };
        addButton.Margin = new Thickness(10);
        addButton.Name = "addButton";
        addButton.Content = "add";

        Button deleteButton = new Button();
        deleteButton.Click += delegate(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(deleteObjectFromLibraryPage), f);
        };
        deleteButton.Margin = new Thickness(10);
        deleteButton.Name = "deleteButton";
        deleteButton.Content = "delete";

        s.Children.Add(addButton);
        s.Children.Add(deleteButton);

        //add new textBlock and stackpanel to existing xaml
        stackPanel.Items.Add(textBlock);
        stackPanel.Items.Add(s);
    }
}

有没有更干净的方法呢?希望我能够传递实际列表而不是FieldInfo。

我不想单独处理每个列表,因为我最终可能会有20多个列表,并且我们以非常类似的方式使用它们。

我想要做的一个例子:

假设我有一个杂货/营养应用程序,我希望用户能够从商店记录他们吃/需要的东西。他们可以从水果,蔬菜,肉类,乳制品,糖果,罐头食品等列表中进行选择。

但是,我希望他们能够(作为高级选项)能够编辑可能的水果列表或任何其他食物类别。而且我不想只列出一份食物和食物清单。因为肉会记录最低烹饪温度之类的东西。

因此,在高级选项下,我希望每个类别有两个按钮(添加到水果,从水果中删除)。理论上添加一个导入/导出页面,这样我就可以与其他人或其他人分享我的水果列表。

看起来指向使用超类的答案似乎不起作用。请参阅:C# polymorphism simple question

1 个答案:

答案 0 :(得分:1)

您可以创建一个列表,以包含您拥有的所有现有列表。然后,您可以遍历列表以创建按钮。如果您希望为每个列表维护一个标签,您可以使用一个字典,其中密钥作为标签文本并列为值。

建议的解决方案除外,请考虑Sayse提供的评论。