Software & Finance





Visual Studio.NET WPF - Adding Buttons and Event Handlers





In Window XAML file, either you can add the following code or you can drag a button from the Toolbox from the designer view. The property Content is used to display the text on the button control. I have added the click event Click="button1_Click" and the event handler in the .cs file will have implemented. I have just added a message box.

 

<StackPanel>

      <Button Content="Click to see the message" HorizontalAlignment="Left"       Margin="26,18,0,0" Name="button1" VerticalAlignment="Top" Height="33"   Width="140" Click="button1_Click" />

</StackPanel>

 

 

private void button1_Click(object sender, RoutedEventArgs e)

{

      System.Windows.MessageBox.Show("Button is clicked from the WPF    application");

}

 

If you look at the event handler button1_Click defined in XAML, that is good enough to invoke the event handler from the programming point of view. However the actual linkage happening in MainWindow.g.cs file with the following code:

 

public partial class MainWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector {

 

      void System.Windows.Markup.IComponentConnector.Connect(int                    connectionId, object target)

      {

 

      switch (connectionId)

      {

 

      this.button1 = ((System.Windows.Controls.Button)(target));

          

      #line 7 "..\..\..\MainWindow.xaml"

      this.button1.Click += new RoutedEventHandler(this.button1_Click);

      #line default

      #line hidden

      return;

      }

      this._contentLoaded = true;

};

 

The following link might look very familiar as it is the way of adding event in C#.

 

this.button1.Click += new RoutedEventHandler(this.button1_Click);

 

In the bottom line you got to understand only one thing - Every thing defined in XAML is getting replaced with temporary *.g.cs code generated by the compiler.