Posted by: Zeeshan Amjad | July 28, 2009

Event Handling with UIElement in WPF


UIElement class introduced the routing event handling and introduced lots of core events. Here is a simple program to show the usages of Event handling of UIElement class.

  1: using System;
  2: using System.Windows;
  3: using System.Windows.Media;
  4: using System.Windows.Input;
  5: 
  6: public class MyUIElement : UIElement
  7: {
  8:     public MyUIElement()
  9:     {
 10:         MouseLeftButtonDown += new MouseButtonEventHandler(OnMouseLeftButtonDown);
 11:     }
 12: 
 13:     protected override void OnRender(DrawingContext dc)
 14:     {
 15:         Rect rect = new Rect(new Point(10, 10), new Point(360, 250));
 16:         LinearGradientBrush gBrush = new LinearGradientBrush(Colors.AliceBlue,
 17:             Colors.Blue, new Point(0, 0), new Point(1, 1));
 18:         dc.DrawRoundedRectangle(gBrush, new Pen(Brushes.Brown, 5), rect, 10, 10);
 19:     }
 20: 
 21:     void OnMouseLeftButtonDown(Object sender, MouseButtonEventArgs e)
 22:     {
 23:         String str = String.Format("Clicked at ({0}, {1})",
 24:             e.GetPosition(this).X, e.GetPosition(this).Y);
 25:         MessageBox.Show(str, "MyUIElement", MessageBoxButton.OK, MessageBoxImage.Information);
 26:     }
 27: }
 28: 
 29: public class MyWindow : Window
 30: {
 31:     public MyWindow()
 32:     {
 33:         Title = "MyUIElement  Class";
 34:         Width = 400;
 35:         Height = 300;
 36:         WindowStartupLocation = WindowStartupLocation.CenterScreen;
 37: 
 38:         Content = new MyUIElement();
 39:     }
 40: }
 41: 
 42: public class wpf
 43: {
 44:     [STAThread]
 45:     public static void Main()
 46:     {
 47:         MyWindow win = new MyWindow();
 48: 
 49:         Application app = new Application();
 50:         app.Run(win);
 51:     }
 52: }
 53: 

The output of this program is one rounded rectangle. When user click on the window then it will display a message box with the point where user clicks on the window. Here is an output of this program. Here is the output of this program.

wpf_21

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: