Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding can only be set on a DependencyProperty of a DependencyObject - when property is overridden with new

Tags:

c#

wpf

xaml

I have a class hierarchy as follows and binding to the VisibleRange property is throwing in the designer.

Given the class hierarchy here:

// Base class
public abstract class AxisBase : ContentControl, IAxis
{
    public static readonly DependencyProperty VisibleRangeProperty = DependencyProperty.Register(
        "VisibleRange", typeof(IRange), typeof(AxisBase), 
         new PropertyMetadata(default(IRange), OnVisibleRangeChanged));

    public IRange VisibleRange
    {
        get { return (IRange)GetValue(VisibleRangeProperty); }
        set { SetValue(VisibleRangeProperty, value); }
    }
}

// Derived class
public class DateTimeAxis : AxisBase
{
        public new IRange<DateTime> VisibleRange
        {
            get { return (IRange<DateTime>)GetValue(VisibleRangeProperty); }
            set { SetValue(VisibleRangeProperty, value); }
        }
}

// And interface definitions
public interface IRange<T> : IRange 
{
}

And designer (XAML) here:

<local:DateTimeAxis Style="{StaticResource XAxisStyle}"                                               
       VisibleRange="{Binding ElementName=priceChart, 
                      Path=XAxis.VisibleRange, Mode=TwoWay}"/>

I get this exception:

A 'Binding' cannot be set on the 'VisibleRange' property of type 'DateTimeAxis'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

The derived class DateTimeAxis is exposing the VisibleRange property which is overridden by the new keyword. I can't add a generic typeparam to the base AxisBase class, and I also need to access the property in both classes. So, I'm wondering given these constraints, if anyone has any suggestions on how to do this better to avoid the designer exceptions?

like image 864
Dr. Andrew Burnett-Thompson Avatar asked Apr 05 '12 21:04

Dr. Andrew Burnett-Thompson


1 Answers

The 'dependency property' is the thing you registered with:

 public static readonly DependencyProperty VisibleRangeProperty = 
    DependencyProperty.Register("VisibleRange", typeof(IRange), typeof(AxisBase), ...);

And when you look at that statement you can see that it is registering with typeof(IRange)

The derived class DateTimeAxis is exposing the VisibleRange property which is overridden by the new keyword.

Yes, but it is exposing a 'normal' property, not a Dependency Property.
Another factor is that the properties have different types.

like image 134
Henk Holterman Avatar answered Oct 23 '22 20:10

Henk Holterman