2016-03-10 176 views
0

我有一個模型實現如下所示的INotifyPropertyChanged。將名稱和城市綁定到標籤很容易。但是我在將玩家綁定到數據網格時遇到了問題。有沒有人有任何提示? (這是所有隻讀信息。)WPF綁定複雜對象

public class Team : INotifyPropertyChanged 
{ 
    private string _name; 
    private string _city; 
    private List<Player> _players; 

    public string Name 
    { 
     get { return _name; } 
    } 

    public string City 
    { 
     get { return _city; } 
    } 

    public List<Player> Players 
    { 
     get { return _players; } 
    } 

} 
public class Player 
{ 
    public int ID {get; set;} 
    public string FirstName {get; set;} 
    public string LastName {get; set;} 
} 
+0

請爲你的'DataGrid'顯示你的XAML代碼。你有什麼嘗試? – devuxer

+0

你無法編譯這個,我編輯了你的代碼,看到我的答案 – Coding4Fun

回答

0

誰知道我以爲我在做什麼。但它現在正在工作。這裏是的ItemSource:

ItemsSource="{Binding Path=Players}" 
0

改變你的團隊類,則必須執行INotifyPropertyChanged這樣的:

public class Team : INotifyPropertyChanged 
    { 
     private string _name; 
     private string _city; 
     private List<Player> _players; 

     public string Name 
     { 
      get { return _name; } 
     } 

     public string City 
     { 
      get { return _city; } 
     } 

     public List<Player> Players 
     { 
      get { return _players; } 
      set { 
       _players =value; 
       RaisePropertyChanged("Players"); 
      } 
     } 


     #region INotifyPropertyChanged 

     internal void RaisePropertyChanged(string prop) 
     { 
      if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(prop)); } 
     } 
     public event PropertyChangedEventHandler PropertyChanged; 

     #endregion 

    } 
    public class Player 
    { 
     public int ID { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
    } 

在組類設置你的主窗口的DataContext的由一個實例是這樣的:

public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      DataContext = new Team 
      { 
       Players = new List<Player>() 
       { 
        new Player{ ID=1, FirstName="Mohammed", LastName="Ali" }, 
        new Player{ ID=2, FirstName="Paul", LastName="Oshain" }, 
       } 
      }; 
     } 
    } 

並最終在您的XAML(您的MainWindow)中做出很好的約束;像這樣:

<Window x:Class="WpfApplication4.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <DataGrid ItemsSource="{Binding Players}" AutoGenerateColumns="False" > 
      <DataGrid.Columns> 
       <DataGridTextColumn Header="Id" Binding="{Binding ID}"/> 
       <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/> 
       <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" /> 
      </DataGrid.Columns> 
     </DataGrid> 
    </Grid> 
</Window>