1

I have two classes, Player and Scorecard. Scorecard has a number of properties, Player also has properties, one of which is a Scorecard object. I then have an array of Players. How do I setup a WPF Datagrid to display a player on each row with Player’s Name property in the first column but the properties from Player’s Scorecard object in the other rows?

Here are the classes...

class Scorecard
    {
        public Scorecard()
        {           
        }

        // Properties
        public int Horses { get; set; } = -1;
        public int Sheep { get; set; } = -1;
        public int Cows { get; set; } = -1;
    }

class Player
    {
        public Player(int playerId, string playerName)
        {
            ID = playerId;
            Name = playerName;
            Scorecard = new Scorecard();
        }

        // Parameters
        public int ID { get; }
        public string Name { get; }
        public Scorecard Scorecard;
    }

and this is what I’m hoping to achieve (excuse the ASCII graphics, I don't have enough reputation points to post an image!)...

| Name   | Horses | Sheep | Cows  |
| Pete   | 12     | 2     | 4     |
| Lucy   | 2      | 8     | 14    |

I’ve searched around and can’t find a solution that’s quite right. The code below gets me the first column but it’s digging into the associated Scorecard object that I can’t work out.

        var col = new DataGridTextColumn();
        var binding = new Binding("Name");
        col.Binding = binding;
        dgScoreGrid.Columns.Add(col);
        dgScoreGrid.ItemsSource = playerArray;

1 Answer 1

1

1st thing is to make Scorecard a property (not field)

// Parameters
// ...
public Scorecard Scorecard { get; }

and than according to Binding Path Syntax, subproperties of a property can be specified by a similar syntax as in C#.

var col = new DataGridTextColumn();
var binding = new Binding("Name");
col.Binding = binding;
dgScoreGrid.Columns.Add(col);

dgScoreGrid.Columns.Add(new DataGridTextColumn{Binding = new Binding("Scorecard.Horses")});

dgScoreGrid.ItemsSource = playerArray;
Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks, that's done the trick. I'd actually tried that syntax but hadn't realised that it only applies to properties, not fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.