DevExpress SchedulerControl示例:虚拟属性与Create()方法等设计疑问
Create() Methods in DevExpress Scheduler MVVM Code? Great question—these patterns are core to how DevExpress's MVVM framework works, especially when pairing with controls like SchedulerControl. Let's break down each piece clearly:
1. Virtual Properties in Model Classes (Schedule & Program)
Marking properties as virtual lets DevExpress's MVVM framework dynamically generate a proxy class that automatically implements INotifyPropertyChanged—the critical interface for syncing property updates with the UI.
Instead of writing repetitive boilerplate code for every property's PropertyChanged event, ViewModelSource creates a subclass of your model, overrides each virtual property, and injects the notification logic under the hood. For example, when you update Schedule.Name, the proxy class triggers the PropertyChanged event instantly, so the SchedulerControl reflects the change without extra work from you.
This also unlocks other DevExpress MVVM features like:
- Built-in data validation rules
- Property dependency tracking
- Full support for their POCO ViewModel pattern
2. Static Create() Methods & Protected Constructors
The static Create() methods (paired with protected constructors) exist to force you to create model instances wrapped by DevExpress's proxy class.
Look at your Schedule code as an example:
public static Schedule Create() { return ViewModelSource.Create(() => new Schedule()); } protected Schedule() { }
- The protected constructor blocks direct instantiation with
new Schedule()—you have to use theCreate()method instead. ViewModelSource.Create()generates the proxy instance we talked about earlier, which includes theINotifyPropertyChangedimplementation and other MVVM hooks the framework needs.
The overloaded Create() methods (like Create(int Id, string Name)) are just convenience helpers—they let you initialize multiple properties in one call instead of setting them one-by-one after creation, while still guaranteeing you get a valid, framework-ready instance.
3. Virtual Collection Properties in MainViewModel
Marking ObservableCollection<Schedule> and ObservableCollection<Program> as virtual serves two key goals:
- Framework Integration: Even though
ObservableCollectionalready implementsINotifyCollectionChanged, making the propertiesvirtuallets DevExpress generate a proxy for yourMainViewModel. This adds enhanced change-tracking logic that's optimized forSchedulerControl's data binding, ensuring smoother UI updates when items are added/removed. - Extensibility: If you ever need to subclass
MainViewModel(e.g., to add custom collection logic for a specific view), thevirtualmodifier lets you override these properties in the subclass—supporting polymorphism and flexible code reuse.
内容的提问来源于stack exchange,提问作者Redzix

