0

I have a DataGrid bound to an ObservableCollection<MachineOrder> where I want to add some columns programmatically.

The object MachineOrder contains another ObservableCollection<KeyValue> from which I want to add the columns.

The thing is that I want to display a specific Key in the ObservableCollection for each row. The index isn't always the same so I cant use that.

I tried it this way:

foreach (StringWrapper characteristic in viewModel.Characteristics)
{
     Binding binding = new Binding();
     binding.FallbackValue = "kein Wert";
     binding.Path = new PropertyPath("Charakteristics.FirstOrDefault(x => x.Key == characteristic.Value).Value");

     DataGridTextColumn columnActive = new DataGridTextColumn();
     columnActive.Header = characteristic.Value;
     columnActive.Width = new DataGridLength(0, DataGridLengthUnitType.Auto);
     columnActive.Binding = binding;
}

But the linq expression does not work here. Btw: viewModel.Characteristics contains a list of characteristics which I want to add to the DataGrid

Any ideas?

1
  • First of all: you should use "Characteristics", not "Charakteristics" (c not k). Although it won't solve your problem.
    – Fratyx
    Nov 16, 2015 at 7:05

1 Answer 1

1

As you know, you can only bind to properties. So to solve the problem, just make a property and bind to it.

First, instead on ObservableCollection<KeyValue> create a custom derived collection to be used inside your MachineOrder class.

public class KeyValueCollection : ObservableCollection<KeyValue>
{
    public Value this[string key]
    {
        get
        {
            var item = this.FirstOrDefault(x => x.Key == key);
            return item != null ? item.Value : null;
        } 
    }
}

The whole purpose is to define a new indexer property by key. Note that I don't have your KeyValue class, so the return type would be different.

Then you can bind to that property like this

foreach (StringWrapper characteristic in viewModel.Characteristics)
{
    // ...
    binding.Path = new PropertyPath("Characteristics[\"" + characteristic.Value + "\"]");
    //...
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.