WPF - Datagrid - Binding

A

Anders Eriksson

I want to bind this class to a Datagrid

class StringClass
{
public string StringNumber {get; set;}
public string Tuning {get; set;}
public List<string> Frets {get; set;}
}

I then have a List<StringClass> Fretboard;

So the result would be:
|#|Tuning|0 |1 |2 |...|<Frets.Count>|
|1| F# |F#|G |G#|...
....

So I was hoping that I could use
dataGrid1.ItemsSource = Fretboard;

But I fail because of the List<string> Frets part. I don't know how many
items there are in Frets. It depends on what the users selects.

How would you solve this?

I'm using VS2010 and .NET 4.0

// Anders
PS! The datagrid will be read only
 
A

Anders Eriksson

I want to bind this class to a Datagrid

class StringClass
{
public string StringNumber {get; set;}
public string Tuning {get; set;}
public List<string> Frets {get; set;}
}

I then have a List<StringClass> Fretboard;

Ok, I have come up with an solution.

Had to change List<string> Frets {get; set;} to
List<FretClass> Frets {get; set;}

class FretClass
{
public string Value {get; set;}

public FretClass(string fretname)
{
Value = fretname;
}
}

Then from MainWindow.xaml.cs I do

DataGridTextColumn col = new DataGridTextColumn();
col.Header = "#";
col.Binding = new Binding("StringNumber");
dataGrid1.Columns.Add(col);

col = new DataGridTextColumn();
col.Header = "Tuning";
col.Binding = new Binding("Tuning");
dataGrid1.Columns.Add(col);
int maxFrets = m_Fretboard[0].Frets.Count;
for (int i = 0; i < maxFrets; i++)
{
col = new DataGridTextColumn();
col.Header = i.ToString();
col.Binding = new Binding("Frets[" + i.ToString() + "].Value");
dataGrid1.Columns.Add(col);
}

dataGrid1.ItemsSource = m_Fretboard;

It works! but there may be some more clever way of doing it, so...

// Anders
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top