2013-10-23 218 views
3

我有一個名爲ChartView的UserControl。在那裏我有一個ObservableCollection類型的Property。我已經在ChartView中實現了INotifyPropertyChanged。註冊屬性作爲依賴屬性

的ChartEntry的代碼是:

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

現在我想用另一種觀點認爲,該控制設定以便通過數據綁定的ChartEntries中的ObservableCollection。如果我嘗試做它用:

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

我得到了,我不能綁定到非依賴屬性或不依賴對象的XAML窗口的消息。

我試圖將ObservableCollection註冊爲DependencyProperty,但沒有成功。 我的代碼試圖從WPF Tutorial

我的附加,房產碼

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?

+0

類是靜態的? –

回答

4

你似乎是一個AttachedPropertyDependencyProperty之間有些困惑。忘掉你ChartEntriesSource類...相反,添加到您的ChartView控制這個DependencyProperty應該做的伎倆:

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); } 
} 
2

您不需要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}"/> 
+1

哦,你很快! :) – Sheridan

+0

haha​​..cheers朋友:) – Nitin