102425074
102425074

Reputation: 811

Why throw the error of "Cannot add content to an object of type" by customcontrol?

I wrote a customcontrol inhert Control and add a DependencyProperty content which I want it to be the same as the content of the button control.

Here is the code:

[System.ComponentModel.Bindable(true)]
public object Content
{
    get { return (object)GetValue(ContentProperty); }
    set { SetValue(ContentProperty, value); }
}

// Using a DependencyProperty as the backing store for Content.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty ContentProperty =
    DependencyProperty.Register("Content", typeof(object), typeof(SContent), null);

But after I reference the dll and run the program, WPF threw this error: enter image description here enter image description here

What's wrong with this? Would you please help me? Thank you.

Upvotes: 1

Views: 738

Answers (1)

mm8
mm8

Reputation: 169340

If you want your custom control to support direct content in XAML, you should decorate it with the ContentPropertyAttribute :

[ContentProperty("Content")]
public class SContent : Control
{
    [System.ComponentModel.Bindable(true)]
    public object Content
    {
        get { return GetValue(ContentProperty); }
        set { SetValue(ContentProperty, value); }
    }

    public static readonly DependencyProperty ContentProperty = 
        DependencyProperty.Register(nameof(Content), typeof(object), typeof(SContent), null);
}

But if you just want a Content property you might as well inherit from ContentControl instead of Control. Then you also get a ContentTemplate property and some other stuff "for free".

Upvotes: 1

Related Questions