简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM