title: Does MouseLeftButtonDown sender object really not pass a referance to object that triggered it? c# Silverlight
body: <p>I recently created a Silverlight 3 app in which I created some UI elements in the code behind and added them at run-time dynamically.</p>
  
  <p>I was hoping to just use the built-in MouseButtonEventArgs or the sender object to get a reference to the instance that was clicked, however I noticed once I started that this was not the case. I was not able to access any properties of the object that triggered the event and program against it.</p>
  
  <pre><code> void myFunc(object sender, MouseButtonEventArgs e)
      {
          //Can't do this :(           
          sender.someProperty = someValueToUpdate;
          //or this
          MyClass foo = sender as MyClass;
          foo.someProperty = someValueToUpdate;
  
      }
  </code></pre>
  
  <p>I ended up just writing a CustomEventArgs object to pass an instance, but it surprised me that this wasn't a default behavior.</p>
  
  <p><strong>Can anyone shed some light as to WHY the sender object doesn't contain a reference to the object that triggered the event?</strong> </p>
  
  <p>Also, here is what I did to get that instance.</p>
  
  <pre><code>myObject.myEvent += new CustomEvent(myFunc);        
  ...
  void myFunc(object sender, CustomEventArgs e)
              {
                   e.MyProperty = someValueToUpdate;
              }
  ...
       public class MyClass 
           {
              public MyProperty = 0;    
              public event CustomEvent myEvent;
              protected virtual void MyEventMethod(CustomEventArgs e)
              {
                  if (myEvent != null){myEvent(this, e);}
              }  
              public MyClass ()
              {
               this.MouseLeftButtonDown += new MouseButtonEventHandler(this_MouseLeftButtonDown);
              }
              void rect_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
              {
                  CustomEventArgs e2 = new CustomEventArgs(this);
                  MyEventMethod(e2);
              }
          }   
  
       public class CustomEventArgs : EventArgs
          {
              private readonly MyClass myProperty;
              public CustomEventArgs(MyClass myProperty) { this.myProperty = myProperty; }
              public MyClass MyProperty { get { return myProperty; } }
          }
       public delegate void CustomEvent(object sender, CustomEventArgs e);
  </code></pre>