2010-08-25 118 views
0

我有類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> 

不用說,這不工作...任何指針爲我在做什麼錯將是有益的.. 提前致謝

回答

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> 

按預期工作。希望這可以幫助。

+0

這個工作..感謝很多 – 2010-08-25 13:53:17

0

使字段公開屬性並實現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

相關問題