开发者

Best way to registered Event In WPF

开发者 https://www.devze.com 2022-12-27 00:25 出处:网络
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 loade

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消