C# - WPF类获取所有资源并填充列表框

时间:2017-08-15 06:37:03

标签: c# wpf listbox listboxitem

我有一个获得所有资源名称的班级。这是代码:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace Helper
{

    public static class callResources
    {

        public static ObservableCollection<string> callAllResources()
        {
            var properties = typeof(Properties.Resources).GetProperties(
      System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |
      System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static);

            ObservableCollection<string> col = new ObservableCollection<string>();
            foreach (var propertyInfo in properties)
            {
                var s = propertyInfo.Name;
                if (s != "ResourceManager" && s != "Culture")
                {
                    col.Add(s);
                }
            }
           return col;
        }
    }
}
MainWindows.cs中的

有以下代码:

public ObservableCollection<string> resourcesListBox
        {
            get
            {
                return callResources.callAllResources();
            }
        }

如果我调用resourcesListBox,我在queryListBox中只有一行。

并且在MainWindow.xaml中有这个但它不起作用:

 <ListBox x:Name="queryListBox" HorizontalAlignment="Left" Height="155" Margin="18,10,0,0" SelectionMode="Single" VerticalAlignment="Top" Width="389"  ItemsSource="{Binding Path = resourcesListBox}" SelectionChanged="listBox_SelectionChanged"/>

2 个答案:

答案 0 :(得分:1)

尝试这种方式:

stringList.ForEach(item => listBox1.Items.Add(item))

答案 1 :(得分:1)

首先,您需要使您的类静态,以便您可以从后面的代码中调用它,而无需创建新实例。

其次,您需要在callAllResources方法中返回类似List或ObservableCollection的内容,并将所有名称放在此列表或ObservableCollection中。

然后你可以从后面的代码调用这个方法,它返回一个列表或资源名称的ObservableCollection。

callResources类:

public static class callResources
  {

    public static ObservableCollection<string> callAllResources()
    {
      var properties = typeof(Properties.Resources).GetProperties(
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static);

      ObservableCollection<string> col = new ObservableCollection<string>();
      foreach (var propertyInfo in properties)
      {
        var s = propertyInfo.Name;
        if (s != "ResourceManager" && s != "Culture")
        {

          col.Add(s);

        }
      }
      return col;
    }
  }
代码背后的代码:

public ObservableCollection<string> resourcesListBox
{
  get
  {
    return callResources.callAllResources();
  }
}

Xaml代码:

<ListBox x:Name="Listbox1" ItemsSource="{Binding Path=resourcesListBox}"/>