Why to run code in method called by XAML Window.Loaded?

风流意气都作罢 提交于 2019-12-04 05:44:25

Yes, there is a similar life cycle for WPF controls, just like in ASP.NET. The life cycle of WPF controls is simpler though, as it basically consits of an initialized, loaded, and unloaded event (in that order). See:

http://msdn.microsoft.com/en-us/library/ms754221.aspx

and Mike Hillberg has an excellent article demonstrating the difference between the initalized and loaded events:

http://blogs.msdn.com/mikehillberg/archive/2006/09/19/LoadedVsInitialized.aspx

Excellent links, Razzie.

Edward - you'll find that the most interresting distinction is that the Contructor as always the first method called on your Window/Page/UserControl and you can't count on all DependencyProperties having been initialized to their final values. Also, it's ill advised to call any virtual methods from within your construtructor.

The Loaded event, by contrast, is generally called at the end of the initialization processes... that is - when the Window/Page/UserControl has been fully loaded into a WPF ElementTree. From within your loaded event, you can confidently call any methods and modify any DepenencyProperty without risk of unexpected results.

A nice pattern (which I'm currently using in my project) is to initialize custom dependency properties in the Loaded event if they haven't been modified during initialization. For controls, this pattern allows you to avoid initializing "expensive" properties (like a DependencyProperty which is an ObservableCollection) if they are being overwritten (i.e. by a property Binding from the calling code).

Simple answer: Use the Loaded event if you're not sure about how to safely overload the constructor.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!