Skip to main content

Initialize a Property After Creating an Object (XPO)

  • 3 minutes to read

Tip

For .NET 6 applications, see: Initialize Business Object Properties (XPO, .NET 6).

In this lesson, you will learn how to set the default value for a particular property of a business class. For this purpose, the Priority property will be added to the DemoTask class created in the Set a Many-to-Many Relationship lesson. To initialize it, the AfterConstruction method will be overridden in this class.

Note

Before proceeding, take a moment to review the following lessons:

  • Add the Priority property to the DemoTask class and declare the Priority enumeration, as shown below:

    public class DemoTask : Task {
        // ...
        private Priority priority;
        public Priority Priority {
            get { return priority; }
            set {
                SetPropertyValue(nameof(Priority), ref priority, value);
            }
        }
        //...
    }
    public enum Priority {
        Low = 0,
        Normal = 1,
        High = 2
    }
    
  • To initialize the newly added Priority property when a DemoTask object is created, override the AfterConstruction method, as shown below:

    [DefaultClassOptions]
    [Custom("Caption", "Task")]
    public class DemoTask : Task {
        //...
        public override void AfterConstruction() {
            base.AfterConstruction();
            Priority = Priority.Normal;
        }
        //...
    }
    

    This method will be executed when the new DemoTask object is created. As a result, the Priority property will be initialized with the specified value. For details on the AfterConstruction method, refer to the PersistentBase.AfterConstruction Method topic in the XPO documentation.

  • Run the WinForms or ASP.NET Web Forms application. Create a new DemoTask object by selecting DemoTask in the drop-down list of the New (new_dropdown_btn) button. (In the Detail View that represents the newly created DemoTask object, note that the Priority property is set to Normal, as declared in the code above.) Notice that the enumeration property is automatically displayed by the combo box editor.

    Tutorial_BMD_Lesson12_1

You can see the code demonstrated in this lesson in the MySolution.Module | Business Objects | DemoTask.cs (DemoTask.vb) file of the Main Demo installed with XAF. The MainDemo application is installed in %PUBLIC%\Documents\DevExpress Demos 22.1\Components\XAF\MainDemo by default. The ASP.NET Web Forms version is available online at https://demos.devexpress.com/XAF/MainDemo.

Next Lesson: Implement Dependent Reference Properties

See Also