如何将集合绑定到WPF中的列表框?
问题描述:
我有类Employee这是类似的东西。如何将集合绑定到WPF中的列表框?
class Emp
{
int EmpID;
string EmpName;
string ProjectName;
}
我有一个list<employee> empList
填充,并希望显示它在列表框中。 我ListBox的的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>
不用说,这不工作...任何指针为我在做什么错将是有益的.. 提前致谢
答
代码隐藏:
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>
按预期工作。希望这可以帮助。
答
使字段公开属性并实现INotifyPropertyChanged。您可能还希望有一个ObservableCollection,而不是一个列表:
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));
}
}
+0
我在网上发现了许多ObservableCollection的例子..但我想知道的是它可能与清单?是的,班上的所有成员都是公开的,我只是想给出一个主意..还有那个 – 2010-08-25 13:29:14
这个工作..感谢很多 – 2010-08-25 13:53:17