我有一个名为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。如果我试着这样做:
<charts:ChartView ChartEntries="{Binding ChartEntriesSource}"/>
我在xaml窗口中收到一条消息,我无法绑定到非依赖项属性或非依赖项对象。
我尝试将ObservableCollection注册为DependencyProperty,但没有成功。 我尝试使用WPF Tutorial
中的代码我的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?
答案 0 :(得分:4)
您似乎在AttachedProperty
和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); }
}
答案 1 :(得分: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}"/>