具有不同类型发送器的EventHandler

本文关键字:EventHandler 同类型 | 更新日期: 2023-09-27 18:25:18

我正在尝试为我在c#for windows phone 8中创建的类型的特定对象实现拖放。我使用的操纵事件是这样的:

deck[r[i, j]].card.ManipulationCompleted += new EventHandler<ManipulationCompletedEventArgs>(ImageManipulationCompleted);
private void ImageManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
    //something
}

如何将对象更改为我想要的类型?

具有不同类型发送器的EventHandler

keyboardP的解决方案可以正常工作。但我个人更喜欢将我需要的信息存储在控件的Tag属性中,该属性正是为此目的而设计的。

deck[r[i, j]].card.Tag = deck[r[i, j]];
deck[r[i, j]].card.ManipulationCompleted += ImageManipulationCompleted;
private void ImageManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
{
    var deck = (Deck)((FrameworkElement)sender).Tag;
}

keyboardP方法的好处是,由于您直接接收所需的对象作为方法的参数,因此读取起来更容易。不利的一面是,您必须为所需的每个事件声明一个自定义委托,并且您失去了直接从XAML分配事件处理程序的能力。我的解决方案有点难以阅读,但解决了这一点。

最终,哪种解决方案更好取决于你的口味和需求。

您所能做的只是调用一个接收type的方法,而不是使用标准的ImageManipulationCompleted处理程序。我不知道deck[r[i, j]]类型是什么,但你可以用正确的类型替换下面的MyType

deck[r[i, j]].card.ManipulationCompleted += delegate(object s, ManipulationCompletedEventArgs e){ CardManipulated(s, e, deck[r[i, j]]); };
private void CardManipulated(object sender, ManipulationCompletedEventArgs e, MyType selectedObject)
{
    //you know have access to selectedObject which is of type deck[r[i, j]],
    //the ManipluationCompletedEvents properties if needed,
    //and the actual card Image object (sender).
}

你不能。

由于您订阅的事件代码为new EventHandler<>(..),因此无法更改sender的类型,因为在EventHandler<>的描述中只有object发送方:

public delegate EventHandler<T>(object sender, T eventArgs) where T : EventArgs

如果你需要创建自己的代理,你可以创建一个工厂,或者简单地写下:

public delegate EventHandler<T, TArgs>(T sender, TArgs eventArgs) where TTArgs : EventArgs

ManipulationCompletedEventHandler签名在其第一个参数中使用对象

public delegate void ManipulationCompletedEventHandler(object sender, 
                         ManipulationCompletedRoutedEventArgs e);

所以,你不能更改签名,但你可以像这样将use delegate to typecast对象始终更改为your type-

deck[r[i, j]].card.ManipulationCompleted += (s, e) => 
           ManipulateMe_ManipulationCompleted((YourType)s, e);
private void ImageManipulationCompleted(YourType sender,
                               ManipulationCompletedEventArgs e)
{
    //something
}

YourType替换为所需的Type(TextBox或其他您想要的东西)