【问题标题】:ObservableCollection as DependenceProperty and binding problemsObservableCollection 作为 DependenceProperty 和绑定问题
【发布时间】:2011-12-11 13:53:47
【问题描述】:

我创建了一个图表控件,过了一段时间我决定向它添加多系列功能。我使用 ObservableCollection<ChartSerie> 类型的依赖属性实现了该功能,如下所示:

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

我使用 XAML 中的这个属性以这种方式调用它:

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

ChartSerie 代码只是 ChartData 的一个容器:

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

我面临的问题是 ChartSerie 实例没有填充来自绑定的数据。它们的 Data 属性始终设置为 null。我在 Visual Studio 的输出中没有绑定错误。

提前致谢。

编辑:经过一番挖掘之后,这里似乎存在真正的绑定问题。看起来 Chart 的 DataContext 没有被 ChartSerie 继承。 ChartSerie 是一个 FrameworkElement 以防万一

【问题讨论】:

    标签: c# wpf xaml binding dependency-properties


    【解决方案1】:

    我记得,您需要定义自己的非泛型集合,而不是公开泛型 ObservableCollection&lt;Whatever&gt;

    public class ChartSeriesCollection : ObservableCollection<ChartSeries>
    {
    }
    
    ...
    
    public static readonly DependencyProperty ChartSeriesProperty = DependencyProperty.Register(
        "ChartSeries",
        typeof(ChartSeriesCollection),
        typeof(MyClass));
    

    如果你不这样做,事情确实会变得很奇怪。

    【讨论】:

    • 嗯......你有什么暗示为什么需要这个吗?无论如何我会检查的。最初,我将通用集合公开为图表的单个依赖属性(只是一个系列的数据,而不是系列列表)并且它正在工作。
    • 我更换了收藏,现在我看到了绑定问题,你能检查我的编辑吗?谢谢!
    • 您应该在第一个问题中将我指向您的博客文章 :) 再次感谢 Kent。
    猜你喜欢
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多