Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

ObservableCollection as DependenceProperty and binding problems

I've created a Chart control and after a while I decided to add multiserie capabilities to it. I implemented the feature using a dependence property of type ObservableCollection<ChartSerie> like this:

private static DependencyPropertyKey SeriesPropertyKey = DependencyProperty.RegisterReadOnly("Series", typeof(ObservableCollection<ChartSerie>), typeof(Chart), new FrameworkPropertyMetadata(new ObservableCollection<ChartSerie>()));
public static DependencyProperty SeriesProperty = SeriesPropertyKey.DependencyProperty;

I use this property from XAML calling it this way:

    <chart:Chart>
        <chart:Chart.Series>
            <chart:ChartSerie Data="{Binding ChartData1}"/>
            <chart:ChartSerie Data="{Binding ChartData2}" />
        </chart:Chart.Series>
    </chart:Chart>

The ChartSerie code is just a container of the ChartData:

public static DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof(ObservableCollection<ChartPoint>), typeof(ChartSerie), new FrameworkPropertyMetadata(OnDataChanged));

The problem I'm facing is that the ChartSerie instances are not being populated with the data coming from the binding. Their Data property is always set to null. I have no binding errors at the output of the visual studio.

Thanks in advance.

EDIT: After digging a bit looks like there is a real binding issue here. Looks like the DataContext of Chart is not inherited by ChartSerie. ChartSerie is a FrameworkElement just in case this matters

Upvotes: 0

Views: 322

Answers (1)

Kent Boogaart
Kent Boogaart

Reputation: 178630

As I recall, you need to define your own non-generic collection rather than exposing a generic ObservableCollection<Whatever>:

public class ChartSeriesCollection : ObservableCollection<ChartSeries>
{
}

...

public static readonly DependencyProperty ChartSeriesProperty = DependencyProperty.Register(
    "ChartSeries",
    typeof(ChartSeriesCollection),
    typeof(MyClass));

If you don't do this, things get very weird indeed.

Upvotes: 1

Related Questions