改變你的團隊類,則必須執行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>
請爲你的'DataGrid'顯示你的XAML代碼。你有什麼嘗試? – devuxer
你無法編譯這個,我編輯了你的代碼,看到我的答案 – Coding4Fun