Skip to content

Customizing using attributes

meziantou edited this page Jun 23, 2015 · 1 revision

You can customize the way properties are shown using attributes:

Setting the property name

By default the name is decamelized. For instance the property FirstName is converted to First Name. If you need to change this name, you can add the DisplayNameAttribute on the property:

public class Customer
{
	[System.ComponentModel.DisplayName("First name")]
	public string FirstName { get; set; }
}

Grouping properties

You can group properties by using the CategoryAttribute:

public class Customer
{
	[System.ComponentModel.Category("Misc")]
	public Guid Id { get; set; }
	
	[System.ComponentModel.Category("Misc")]
	public DateTime CreationDate { get; set; }

	[System.ComponentModel.Category("Identity")]
	public string FirstName { get; set; }
	[System.ComponentModel.Category("Identity")]
	public string LastName { get; set; }
	[System.ComponentModel.Category("Identity")]
	public DateTime DateOfBirth { get; set; }

	[System.ComponentModel.Category("Security")]
	public SecureString Password { get; set; }
}

Hidding properties

In some cases you prefer hidding some properties. For instance to hide the property Id, you have to decorate it with the BrowsableAttribute:

public class Customer
{
    [System.ComponentModel.Browsable(false)]
    public Guid Id { get; set; }
}

Default values

Properties always have a default value. For instance the default value for an int is 0, and for a string it's null. You can change this behavior by using the DefaultValueAttribute:

public class Customer
{
    [System.ComponentModel.DefaultValue(true)]
    public bool IsActive { get; set; }
}

ReadOnly

To prevent a user from changing the value of a property, even if the property has a setter, you can use the ReadOnlyAttribute. The property grid will display the value, but the user won't be able to change it.

public class Customer
{
    [System.ComponentModel.ReadOnly(true)]
    public Guid Id { get; set; }
}

Changing the sort order

There is no default attributes to set the sort order so we create the PropertyGridOptionsAttribute.

public class Customer
{
	[SoftFluent.Windows.PropertyGridOptions(SortOrder = 10)]
	public string FirstName { get; set; }

	[SoftFluent.Windows.PropertyGridOptions(SortOrder = 20)]
	public string LastName { get; set; }

	[SoftFluent.Windows.PropertyGridOptions(SortOrder = 30)]
	public DateTime DateOfBirth { get; set; }
}