new does not hide an inherited property

1.5k views Asked by At

Possible Duplicate:
C# keyword usage virtual+override vs. new

I'm trying to hide my UserControl Content property in the following way:

public partial class Tile : UserControl
{
    public new object Content
    {
        get { ... }
        set { ... }
    }
}

But when I set the Content of my UserControl it does not do anything (if I set a breakpoint it is never reached):

<my:Tile Content="The content"/>

or

<my:Tile>The content</my:Tile>

Why? How can I solve this problem?

2

There are 2 answers

3
Mike Marynowski On

The problem is that you aren't hiding the actual DependencyProperty, only the get/set accessor which WPF may or may not always use to set the value of the DP. WPF has optimizations that directly call DependencyObject.GetValue/SetValue instead.

Create a dependency property on your object with the name "Content" instead and then new up the get/set accessors and what you are doing should work.

public static readonly new DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(object), typeof(Tile));

public new object Content
{
    get { return this.GetValue(ContentProperty); }
    set { this.SetValue(ContentProperty, value); }
}

I'm not sure why you would want to do this though, instead of just using the content property that is already there. It would seem to me that you are fighting the framework here and there's an easier way to do what you want.

0
Adi Lester On

If you'd like to plug-in your own functionality to the Content property, what you're probably looking for is DependencyProperty.OverrideMetadata(). This way you can add your own property changed handler in your derived class. It would look something like this:

static Tile()
{
    ContentProperty.OverrideMetadata(typeof(Tile), new PropertyMetadata(null, OnContentChanged));
}

private static void OnContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    // Your logic goes here.
}

EDIT

Just had a look, and WPF already took care of this for you. You can simply override OnContentChanged:

protected override void OnContentChanged(object oldContent, object newContent)
{
    base.OnContentChanged(oldContent, newContent);

    // Your logic goes here.
}