1

有什么方法可以制作 WPF 中所需的自定义属性?

我的意思是当我在设计器中的自定义属性未填充时出现错误消息?例如:必填=“真/假”

我的自定义属性定义:

public static readonly DependencyProperty AaFunctionalUnitNameProp;
    [Category(VsCategoryName.AaObjectInfo)]
    [Description(VsPropertyDescription.FunctionalUnitName)]
    public string AaFunctionalUnitName
    {
        get => (string)GetValue(AaFunctionalUnitNameProp);
        set => SetValue(AaFunctionalUnitNameProp, value);
    }
4

1 回答 1

1

没有开箱即用的功能可以执行此操作,但是您可以分配一个无效的(根据您的定义)默认值,并且在您的OnInitialized事件中,当它仍然是默认值时抛出异常(仅在不处于设计模式时课程)。

例子:

public class CustomControl : Control
{
    public static readonly DependencyProperty RequiredPropertyProperty = DependencyProperty.Register(
        "RequiredProperty", typeof(int), typeof(CustomControl), new PropertyMetadata(int.MinValue));

    public int RequiredProperty
    {
        get { return (int) GetValue(RequiredPropertyProperty); }
        set { SetValue(RequiredPropertyProperty, value); }
    }

    protected override void OnInitialized(EventArgs e)
    {
        if(RequiredProperty == int.MinValue)
            if(!DesignerProperties.GetIsInDesignMode(this))
                throw new Exception("RequiredProperty must be explicitly set!");

        base.OnInitialized(e);
    }
}
于 2017-09-21T12:52:51.957 回答