Question : Silverlight 4 UI Events

I have a silverlight app with some buttons dynamically added at run time.

I added MouseLeftButtonUp and MouseLeftButtonDown mouse events and the methods they points to do not get raised on the mouse click.  If I add a click event or mouse enter/move events those methods do end up being raised however these events are of no use to me at this time.  What could cause this?

A co-worker mentioned the silverlight controls act like browser controls so I might need to add some Javascript to use these events.  If so is there a reference someone can point to for me to use.

I am coding Silverlight 4 on VS2010.

Thanks.

Answer : Silverlight 4 UI Events

Hi,

I think this comes down to routed events... not a subject i've read a great deal on - but will do now!

anyway, to solve your problem you need to call AddHandler to attach your handler to the routed events you're interested in. I've attached a code sample to illustate this.

HTH

Mike
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
public partial class MainPage : UserControl
    {
        private ListBox lb;

        public MainPage()
        {
            InitializeComponent();
            Button btn = new Button();
            btn.Content = "Press Me!";

            // btn.Click is a routed event
            btn.Click += new RoutedEventHandler(btn_Click);


            // btn.MouseLeftButtonUp is not a routed event, so attach 
            // to it via the Button.MouseLeftButtonUpEvent instead
            btn.AddHandler(Button.MouseLeftButtonUpEvent,
                new MouseButtonEventHandler(btn_MouseLeftButtonUp),
                true);

            // btn.MouseLeftButtonDown is not a routed event, so attach 
            // to it via the Button.MouseLeftButtonDownEvent instead
            btn.AddHandler( Button.MouseLeftButtonDownEvent,
                new MouseButtonEventHandler(btn_MouseLeftButtonDown),
                true);

            lb = new ListBox();

            this.LayoutRoot.Children.Add(btn);
            this.LayoutRoot.Children.Add(lb);
        }

        void btn_Click(object sender, RoutedEventArgs e)
        {
            lb.Items.Add("btn_Click");
        }
        
        void btn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            lb.Items.Add("btn_MouseLeftButtonDown");
        }
        void btn_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            lb.Items.Add("btn_MouseLeftButtonUp");
        }
    }
Random Solutions  
 
programming4us programming4us