So i tried for some time to find a case like mine but couldnt really find anything helpfull.
My problem is that i have a datagrid where i need to have 2 columns with Assignmentnames and the creators of the assignments. Ive allready created the colums with their headers as you can see below.
<DataGrid AutoGenerateColumns="False" Height="257" HorizontalAlignment="Left"
Margin="12,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="479">
<DataGrid.Columns>
<DataGridTextColumn Header="Assignments" />
<DataGridTextColumn Header="Creator" />
</DataGrid.Columns>
</DataGrid>
Furthermore i tried lining this code up as a test. For the final solution i will get the list of assignments from a database but im not at that point yet.
public MainWindow()
{
InitializeComponent();
assignment1 = new Assignment();
assignment2 = new Assignment();
assignments = new List<Assignment>();
assignment1.AddBasicInformation("Engelsk A", "Hans Rueløkke", "Han gik en tur", 0);
assignment1.AddBasicInformation("Historie B", "Lis Hansen", "Hvad hed den første mand på månen? ___.", 0);
assignments.Add(assignment1);
assignments.Add(assignment2);
for(int i = 0; i < assignments.Count; i++)
{
dataGrid1.Items.Add(assignments);
}
}
As you can see the assignments contain 3 strings, an integer and furthermore they contain a couple of lists. The only information i want to be shown in the datagrid however is the first 2 strings. Anyone that can help me how to achieve that?
Editted the important part of my assignment class looks like this
public class Assignment
{
private string name;
private string creator;
private string assignmentText;
private int type;
private List<Answer> answerlist;
public void AddBasicInformation(string aname, string acreator, string aassignmentText, int atype)
{
name = aname;
creator = acreator;
assignmentText = aassignmentText;
type = atype;
answerlist = new List<Answer>();
}
public string GetName()
{
return name;
}
public string GetCreator()
{
return creator;
}
In the constructor, replace the for loop with:
In the XAML, you can then declare the binding of the column (assuming the Assignment class has properties named Assignemnts and Creator):
The binding of the ItemsSource is an anti-pattern in this example, but it will get you started.
For more info, see the WPF DataGrid Class.
Edit: In response to updated code samples by OP
All binding in WPF must be done with Properties. Update your Assignments Class to use Properties instead of fields: