[英]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).
我目前正在用WPF编写一个程序,一个基本的商店程序/界面。我有一个班卓琴类,它具有班卓琴名称,班卓琴ID,班卓琴状态(缺货,进货)等特性。 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>();
我还有一个名为cStock的类,该类具有存储所有班卓琴的静态成员列表,因此,
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. 好的,在我的WPF程序中,我有一个listBox,它用来一一显示班卓琴名称。 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.
我还可以添加班卓琴/创建班卓琴,因此,如果我创建两个班卓琴,它们的名称将分别为“ Banjo1”和“ Banjo2”,我希望它仅显示其名称,而不显示其他名称。 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
. 我已经将listBox的itemsource设置为banjo列表,例如此
listBox_BanjoList.ItemsSource = cStock.BanjoList
,但是我真正想要的是类似于listBox_BanjoList.ItemsSource = cStock.BanjoList.banjoName
。
You have to specify an ItemTemplate
for your ListView
, eg something like this: 您必须为
ListView
指定一个ItemTemplate
,例如:
<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. 但是,首选方法是用户
poke
指示的内容。 With WPF, you should be using MVVM, which can allow you to bind your ListBox
to a List
property. 使用WPF,您应该使用MVVM,它可以使
ListBox
绑定到List
属性。
Example ViewModel: 示例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: XAML:
<ListBox ItemsSource="{Binding BanjoList}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding BanjoName}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Xaml.cs: Xaml.cs:
public partial class MyWindow : Window
{
public MyWindow()
{
InitializeComponent();
DataContext = new MyViewModel();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.