Reputation: 876
I'm trying to bind a list of class A:
class ClassA
{
public int Number;
public int[,] AnArray;
}
To my DataGrid:
<DataGrid Name="ResultsDataGrid" DataContext="{Binding ResultsForGrid}" ItemsSource="{Binding Path=ResultsForGrid}" AutoGenerateColumns="False" Margin="0,10,176,0" Height="220.378" VerticalAlignment="Top" >
<DataGrid.Columns>
<DataGridTextColumn Header="Number" Binding="{Binding Path=Number}"/>
<DataGridTextColumn Header="Array Rows" Binding="{Binding Path=AnArray.GetLength(0)}"/>
<DataGridTextColumn Header="Array Columns" Binding="{Binding Path=AnArray.GetLength(1)}"/>
</DataGrid.Columns>
</DataGrid>
To bind it I'm using a List<ClassA> ResultsForGrid;
which contains all the elements I'll ever want to show in the view and is declared as a global variable in my window class. When my list is filled with all the elements of ClassA I need to display I set the ItemsSource like
ResultsDataGrid.ItemsSource = ResultsForGrid;
The odd thing is that when I run the code I get a dataGrid with the correct headers and correct number of rows (number of elements in ResultsForGrid) but completely empty.
I've tried many combinations of Bindings and DataContext since this view seems to be prone to get questions on the web but all to no avail.
Upvotes: 1
Views: 767
Reputation: 3787
Your
class ClassA
{
public int Number;
public int[,] AnArray;
}
should implement INotifyPropertyChanged
and fields should be replaced by properties:
private _number;
public int Number
{
get { return _number; }
set
{
_number= value;
OnPropertyChanged();
}
}
You can't use methods in XAML:
<DataGridTextColumn Header="Array Rows" Binding="{Binding Path=AnArray.GetLength(0)}"/>
Create property that wraps this AnArray.GetLength(0)
and bind to that property.
You also need class that wraps List<ClassA>
and the instance of that class should be DataContext
of your DataGrid
instance.
Upvotes: 3