简体   繁体   English

将事件处理程序添加到控件中,哪种方法更正确?

[英]Add a event handler to a control, Which way is more correct?

Add a event handler to the button control, Can be done in XAML 将事件处理程序添加到按钮控件,可以在XAML中完成

<Button x:Name="button" Click="Button_Click" />

Can also be done in C# code 也可以用C#代码完成

button.Click += Button_Click;

Which way is more correct? 哪种方法更正确?

Both are not ideal as you are supposed to use WPF with MVVM so you should dig into Databinding and Commands. 两者都不理想,因为您应该将WPF与MVVM一起使用,因此您应该深入研究数据绑定和命令。 However, if you decide to ignore most features WPF gives you over WinForms and want to do it the old way it really comes down to personal preference on whether you like to do it in code or XAML. 但是,如果您决定忽略大多数功能,则WPF会让您胜过WinForms,并希望以旧的方式进行操作,这实际上取决于您是否喜欢用代码或XAML进行操作。 Doing it in XAML however, has the advantage that you do not need to give a name to the control which will not make the button stay loaded in certain situations and save memory and improve program performance 但是,在XAML中这样做的好处是,您无需为控件命名,在某些情况下不会使按钮保持加载状态,从而节省了内存并提高了程序性能。

if you want to use Events use them like this: 如果要使用事件,请按以下方式使用它们:

<Button Click="Button_Click" />

And do not give names to controls. 并且不要给控件起名字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 哪种事件处理程序实现可提高性能? - Which implementation of event handler give more performance? 如何在同一事件处理程序中添加事件处理程序以进行控制? - How to add an event handler to control inside the same event handler? 哪种方法更好或更正确,为什么? - which way is better, or more correct, and why? 将事件委托添加到ASP.NET用户控件的事件处理程序 - Add event delegate to event handler of ASP.NET user control 如何在运行时向事件添加更通用的事件处理程序 - How to add a more generic event handler to an event at runtime 如何检查使用一键事件处理程序单击的控件 - How to check which control is clicked with one click event handler 在其基础的事件处理程序之前使继承的事件处理程序触发的正确方法是什么? - What is the correct way to make an inherited event-handler fire before its base’s event-handler? 在 1 个控件中添加 2 个事件处理程序 - Adding 2 Event Handler in 1 Control 从自定义对象向用户控件添加事件处理程序 - Add Event Handler to User Control from custom object 在自定义TextBox控件的构造函数中添加Validating事件处理程序 - Add Validating event handler in constructor of a custom TextBox control
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM