Is there any way to make a custom property required in WPF?
I mean something like error message when my custom property in designer is not filled? E.g.: Required="true/false"
My custom property definition:
public static readonly DependencyProperty AaFunctionalUnitNameProp;
[Category(VsCategoryName.AaObjectInfo)]
[Description(VsPropertyDescription.FunctionalUnitName)]
public string AaFunctionalUnitName
{
get => (string)GetValue(AaFunctionalUnitNameProp);
set => SetValue(AaFunctionalUnitNameProp, value);
}
There is no out-of-the-box feature that does this, however you could assign an invalid (by your definition) default value and in your OnInitialized
event throw an exception when it's still the default value (Only when not in design-mode of course).
Example:
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);
}
}