Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register Property as DependencyProperty

I have a UserControl called ChartView. There I have a Property of type ObservableCollection. I have implemented INotifyPropertyChanged in the ChartView.

The code for a ChartEntry is:

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

Now I want to use this Control in another View and setting the ObservableCollection for the ChartEntries through DataBinding. If I try to just do it with:

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

I get a message in the xaml-window that I can not bind to a non-dependency-property or non-dependency-object.

I tried to register the ObservableCollection as a DependencyProperty, but with no success. I tried it with the code from WPF Tutorial

My code for the Attached-Property is

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

This also didn't work. How do I register my Property as a DependencyProperty?

like image 600
Tomtom Avatar asked Nov 27 '25 02:11

Tomtom


1 Answers

You seem to be somewhat confused between an AttachedProperty and a DependencyProperty. Forget about your ChartEntriesSource class... instead, adding this DependencyProperty into your ChartView control should do the trick:

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); }
}
like image 114
Sheridan Avatar answered Nov 28 '25 16:11

Sheridan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!