为什么通过customcontrol抛出“无法向类型的对象添加内容”错误?

时间:2019-03-01 15:07:28

标签: wpf

我编写了一个customcontrol继承项Control,并添加了一个DependencyProperty content,我希望它与按钮控件的content相同。

代码如下:

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

但是在我引用dll并运行程序之后,WPF抛出了此错误: enter image description here enter image description here

这是怎么了?你能帮我吗?谢谢。

1 个答案:

答案 0 :(得分:1)

如果您希望自定义控件支持XAML中的直接内容,则应使用ContentPropertyAttribute 装饰它:

==

但是,如果您只想要if(p = NULL) // Valid syntax ... if(NULL = p) // Syntax error ... 属性,则最好从[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); } 继承而不是Content。然后,您还将获得ContentControl属性和“免费”的其他内容。