我有类Employee,就像这样。
class Emp
{
int EmpID;
string EmpName;
string ProjectName;
}
我已填充list<employee> empList
,并希望在列表框中显示它。
我将列表框的itemsource属性设置为empList
,我的XAML代码如下
<ListBox Name="lbEmpList">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding Path=EmpID}"></Label>
<Label Content="{Binding Path=EmpName}"></Label>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
不用说这不起作用...任何指针,因为我做错了会有所帮助.. 提前谢谢你
答案 0 :(得分:1)
代码隐藏:
public partial class Window1 : Window, INotifyPropertyChanged
{
private List<Emp> _empList = new List<Emp>();
public Window1()
{
EmpList.Add(new Emp {EmpID = 1, EmpName = "John", ProjectName = "Templates"});
EmpList.Add(new Emp { EmpID = 2, EmpName = "Smith", ProjectName = "Templates" });
EmpList.Add(new Emp { EmpID = 3, EmpName = "Rob", ProjectName = "Projects" });
InitializeComponent();
lbEmpList.DataContext = this;
}
public List<Emp> EmpList
{
get { return _empList; }
set
{
_empList = value;
raiseOnPropertyChanged("EmpList");
}
}
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void raiseOnPropertyChanged (string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
public class Emp
{
public int EmpID { get; set;}
public string EmpName { get; set; }
public string ProjectName { get; set; }
}
XAML:
<Grid x:Name="grid" ShowGridLines="True">
<ListBox Name="lbEmpList" ItemsSource="{Binding EmpList}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding Path=EmpID}"></Label>
<Label Content="{Binding Path=EmpName}"></Label>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
按预期工作。希望这会有所帮助。
答案 1 :(得分:0)
将字段设为公共属性并实现INotifyPropertyChanged。您可能还想要一个ObservableCollection而不是List:
class Emp :INotifyPropertyChanged
{
int _empId;
public int EmpId
{
get { return _empId; }
set { _empId = value; NotifyChanged("EmpId"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}