Events in WPF works same as in Win Form application except some new concept such as  Routed Event  ( I will blog it in next post).So directly we can jump to the code to add simple events to application as well as Window(Forms in WPF are called as Window ,for XBAP it called as Page).

There are 2 ways of adding events

  1. Declarative Way ( XAML Approach )
  2. Code Way (Conventional as in Win form / Code Approach)

So consider  the scenario bellow and the way to do it in both ways

Scenario 1 –: On Start of our Application we will show the application details.

Through XAML

As we should on load of application the event must be declared in the app.XAML or app.xaml.cs.Write the the event name we want to invoke , the intellisense will prompt as follows

www.manaspatnaik.com/blog Once you click image , it will add a handler to the app.xaml.cs .And there we will have the application information.

Basics What is  Event Handler ?
Code Snippet
  1. /// Interaction logic for App.xaml
  2. /// </summary>
  3. public partial class App : Application
  4. {
  5. private void Application_Startup(object sender, StartupEventArgs e)
  6. {
  7. MessageBox.Show(Environment.Version + “\n” + Environment.UserName
  8. ,“My First WPF Application”);
  9. }
  10. }

Through CODE –:

As the OnStartup is application related event we will override in the app.xaml.cs.

image

Code Snippet
  1. protected override void OnStartup(StartupEventArgs e)
  2. {
  3. MessageBox.Show(Environment.Version + “\n” + Environment.UserName
  4. , “My First WPF Application”);
  5. }

Scenario 2 –: On Button Click display application information (Attaching a event to a method)

Through XAML –:

First we will create a EventHandaler in the the window , as bellow .

Code Snippet
  1. public partial class MyFirstWindow : Window
  2. {
  3. public MyFirstWindow()
  4. {
  5. InitializeComponent();
  6. }
  7. private void ShowApplicationInfo(object sender,RoutedEventArgs e)
  8. {
  9. MessageBox.Show(Environment.Version + “\n” + Environment.UserName
  10. ,“My First WPF Application”);
  11. }
  12. }

Now we will attach the event to the button click in through xaml .

image So the final Xaml code will look like this.

Code Snippet
  1. <Grid>
  2. <Label>My First WPF Application</Label>
  3. <Button Content=”Show About” Height=”50″ HorizontalAlignment=”Left” Margin=”71,78,0,0″
  4. Name=”btnShowAbout” VerticalAlignment=”Top” Width=”143″
  5. Click=”ShowApplicationInfo”
  6. />
  7. </Grid>

Through CODE–:

Code way is same as previous we need to attach the event to the handler on load.

image and the final code will be

Code Snippet
  1. private void ShowApplicationInfo(object sender,RoutedEventArgs e)
  2. {
  3. MessageBox.Show(Environment.Version + “\n” + Environment.UserName
  4. ,“My First WPF Application”);
  5. }
  6. private void Window_Loaded(object sender, RoutedEventArgs e)
  7. {
  8. btnShowAbout.Click += new RoutedEventHandler(ShowApplicationInfo);
  9. }

That’s it .