【发布时间】:2010-02-01 18:59:46
【问题描述】:
我最近创建了一个 Silverlight 3 应用程序,其中我在后面的代码中创建了一些 UI 元素,并在运行时动态添加它们。
我希望只使用内置的 MouseButtonEventArgs 或 sender 对象来获取对被点击的实例的引用,但是我注意到一旦我开始,情况并非如此。我无法访问触发事件的对象的任何属性并针对它进行编程。
void myFunc(object sender, MouseButtonEventArgs e)
{
//Can't do this :(
sender.someProperty = someValueToUpdate;
//or this
MyClass foo = sender as MyClass;
foo.someProperty = someValueToUpdate;
}
我最终只是编写了一个 CustomEventArgs 对象来传递一个实例,但令我惊讶的是这不是默认行为。
谁能解释一下为什么发送者对象不包含对触发事件的对象的引用?
另外,这是我为获得该实例所做的。
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);
【问题讨论】:
-
您是否附加了调试器并查看“sender”的值是多少?
-
是的,它只是一个对象,我可以用 var foo = sender as MyClass; 委托一个类型;但该对象的更新属性不起作用。
标签: c# silverlight