0

I already spent hours on this, and similar topics did not help. :(

I've got an object of type "Chart" which contains a List "LineItems". I want to bind LineItems programmatically to a DataGrid in an UserControl.

Usercontrol XAML:

<DataGrid Name="myData" AutoGenerateColumns="True">

Usercontrol Code behind:

    public void SetItemSource(ChartingBase.Chart chart)
    {
        //DataGrid.ItemsSource = chart.LineItems; // working!

        // this is not working:
        this.DataContext = chart;
        Binding b = new Binding( "LineItems" );
        b.Mode = BindingMode.TwoWay;
        b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        myData.SetBinding( DataGrid.ItemsSourceProperty, b );
    }

Setting just the ItemsSource works. Creating the binding manually does not work and I have no clue what else I could try. Thanks!

flowschi
  • 1
  • 1
  • 2

2 Answers2

0

Try

BindingOperations.SetBinding(myData, DataGrid.ItemsSourceProperty, new Binding("LineItems") { Source = chart });
d.moncada
  • 16,900
  • 5
  • 53
  • 82
-1

In WPF, it is customary to put your data into an ObservableCollection<T> collection and data bind that to the DataGrid.ItemsSource property. Then you can fill or manipulate the collection in code and the UI will update automatically. Try this:

<DataGrid Name="myData" ItemsSource="{Binding Items}" AutoGenerateColumns="True">

...

public void SetItemSource(ChartingBase.Chart chart)
{
    this.DataContext = chart;
    Items = new ObservableCollection<YourDataType>();
    foreach (SomeDataType dataType in chart.SomeCollection)
    {
        Items.Add(new YourDataType(dataType.SomeProperty, ...));
    }
}
Sheridan
  • 68,826
  • 24
  • 143
  • 183
  • Thanks. ObservableCollection - okay. But: if Items is a collection inside my Usercontrol, I have to set the DataContext to 'Self', right? And I can't use copies of my objects. – flowschi Mar 13 '14 at 22:44
  • I'm not sure what that means and I don't know where your data is coming from... it was just an example. Fill your collection anyway you want. – Sheridan Mar 13 '14 at 22:53