简体   繁体   中英

How to get properties of the class that a generic list uses

Didn't know a good title for this but anyway. I am currently making a program in WPF, a basic shop program/interface.I have a banjo class with proprieties such as the banjo name, banjoID, banjo state(out,instock). I have another class called cStock which has a static member list that stores all the banjos, so static List<cBanjo> banjoList = new List<cBanjo>();

Ok so on my WPF program, I have a listBox, that is meant to show the banjo names one by one. I can add banjo/create banjos aswell, So if I create two banjos, their names will be "Banjo1" and "Banjo2", I want it to show their names only, nothing else. The problem is I have no idea how to do it.

I have set the itemsource of the listBox, to the banjo list, like this listBox_BanjoList.ItemsSource = cStock.BanjoList , but what I really want is something along the lines of listBox_BanjoList.ItemsSource = cStock.BanjoList.banjoName .

You have to specify an ItemTemplate for your ListView , eg something like this:

<ListView ItemsSource="{Binding BanjoList}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding banjoName}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

You chould simply do..

listBox_BanjoList.ItemsSource = cStock.BanjoList.Select(banjo => new string(banjo.banjoName.ToCharArray()));

but, the preferred method is what user poke indicated. With WPF, you should be using MVVM, which can allow you to bind your ListBox to a List property.

Example ViewModel:

public class MyViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Banjo> _banjoList;
    public ObservableCollection<Banjo> BanjoList
    {
        get { return _banjoList; }
        set
        {
            _banjoList = value;
            RaisePropertyChanged("BanjoList");
        }
    }

    public MyViewModel()
    {
        // populate list
    }
}

Xaml:

<ListBox ItemsSource="{Binding BanjoList}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding BanjoName}" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

Xaml.cs:

public partial class MyWindow : Window
{
    public MyWindow()
    {
        InitializeComponent();
        DataContext = new MyViewModel();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM