简体   繁体   中英

How to handle App.XAML events in Main.cs?

I would like to know how I handle events that I set in my App.XAML file in a standard WPF configuration. I have a button in my App.XAML file and I would like to add an event handler which is located in my Main.CS file.

Example code:

xmlns:local="clr-namespace:MyApp"

<Button Click="Myhandler" />

Even though App.CS and Main.CS both share the same namespace I get an error saying that my handler does not exist. How can I set the context in the right way?

That's because the class of your App.xaml is MyApp.App :

<Application x:Class="MyApp.App"
   ...
>

xmlns:local="clr-namespace:MyApp" is just like adding a using local = MyApp; line to the beginning of ac# code.

You have to create your event handlers in MyApp.App. but if you're concerned about the Right way to do it you should use Commands instead of event handlers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM