将属性注册为DependencyProperty

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

ChartEntry的代码是:

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

现在我想在另一个View中使用此Control,并通过DataBinding为ChartEntries设置ObservableCollection。 如果我试着这样做:

  

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

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

我的Attached-Property代码是

  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?

您似乎在AttachedPropertyDependencyProperty之间有点混淆。 忘掉你的ChartEntriesSource类……相反,将这个DependencyProperty添加到ChartView控件中应该可以解决这个问题:

 public static readonly DependencyProperty ChartEntriesProperty = DependencyProperty. Register("ChartEntries", typeof(ObservableCollection), typeof(ChartView)); public ObservableCollection ChartEntries { get { return (ObservableCollection)GetValue(ChartEntriesProperty); } set { SetValue(ChartEntriesProperty, value); } } 

你这里不需要AttachedProperty 。 在ChartView添加DependencyProperty类的

  public static readonly DependencyProperty ChartEntriesProperty = DependencyProperty.Register("ChartEntries", typeof(ObservableCollection), typeof(ChartView), new FrameworkPropertyMetadata(OnChartEntriesChanged)); private static void OnChartEntriesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { } 

现在您可以绑定ChartEntries属性: