Which is the b开发者_C百科est way to registered event for example if I wanto to regiested Loaded event for the window or user control , then it is better to registered in the xaml file or in the loaded/initilization function in code behind (C#/VB.net)? Please give explaination of your answer.
The registering of the event handler for the Loaded event, when done in XAML, is done by a generated partial class during the InitializeComponent()
call in your code behind's constructor.
With that explained:
In XAML: You immediately see that there is a Loaded event handler when you look at the XAML. It isn't "hidden" in code somewhere. Additionally, with MVVM, you often have no/negligible code-behind. That way, you can decide to change your control to a DataTemplate, which automatically hooks up the ViewModel as DataContext.
In code-behind: You may have some complicated expression, which is difficult/impossible to express in XAML. For example, you might get the handler from a container or factory. Then you could hook up the event in code-behind.
In general, unless you have specific reasons, I would choose the XAML-route.
精彩评论