3

我有一个名为 ChartView 的用户控件。我有一个 ObservableCollection 类型的属性。我在 ChartView 中实现了 INotifyPropertyChanged。

ChartEntry 的代码是:

public class ChartEntry
{
   public string Description { get; set; }
   public DateTime Date { get; set; }
   public double Amount { get; set; }
}

现在我想在另一个视图中使用这个控件,并通过 DataBinding 为 ChartEntries 设置 ObservableCollection。如果我尝试这样做:

<charts:ChartView ChartEntries="{Binding ChartEntriesSource}"/>

我在 xaml 窗口中收到一条消息,提示我无法绑定到非依赖属性或非依赖对象。

我尝试将 ObservableCollection 注册为 DependencyProperty,但没有成功。我用WPF 教程中的代码试过了

我的附加属性代码是

 public static class ChartEntriesSource
    {
        public static readonly DependencyProperty ChartEntriesSourceProperty =
            DependencyProperty.Register("ChartEntriesSource",
                                                typeof(ChartEntry),
                                                typeof(ChartView),
                                                new FrameworkPropertyMetadata(OnChartEntriesChanged));

        private static void OnChartEntriesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {

        }

        public static void SetChartEntriesSource(ChartView chartView, ChartEntry chartEntries)
        {
            chartView.SetValue(ChartEntriesSourceProperty, chartEntries);
        }

        public static ChartEntry GetChartEntriesSource(ChartView chartView)
        {
            return (ChartEntry)chartView.GetValue(ChartEntriesSourceProperty);
        }
    }

这也没有奏效。如何将我的属性注册为 DependencyProperty?

4

2 回答 2

4

您似乎在 aAttachedProperty和 a之间有些混淆DependencyProperty。忘记你的ChartEntriesSource课程......相反,将它添加DependencyProperty到你的ChartView控件中应该可以解决问题:

public static readonly DependencyProperty ChartEntriesProperty = DependencyProperty.
Register("ChartEntries", typeof(ObservableCollection<ChartEntry>), typeof(ChartView));

public ObservableCollection<ChartEntry> ChartEntries
{
    get { return (ObservableCollection<ChartEntry>)GetValue(ChartEntriesProperty); }
    set { SetValue(ChartEntriesProperty, value); }
}
于 2013-10-23T12:53:26.683 回答
3

你不需要AttachedProperty这里。在你ChartView添加DependencyProperty喜欢

    public static readonly DependencyProperty ChartEntriesProperty =
        DependencyProperty.Register("ChartEntries",
                                            typeof(ObservableCollection<ChartEntry>),
                                            typeof(ChartView),
                                            new FrameworkPropertyMetadata(OnChartEntriesChanged));

    private static void OnChartEntriesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {

    }

现在您可以绑定您的 ChartEntries 属性:

 <charts:ChartView ChartEntries="{Binding PROPERTYOFYOURDATACONTEXT}"/>
于 2013-10-23T12:51:52.163 回答