Addhandler与+ =处理程序语法不同

时间:2013-05-07 11:54:40

标签: c# ironpython routed-events

有人问过c#类似的问题:Is using AddHandler functionally different from Event += Method?

但是我的研究给出了不同的结果,反对那里给出的答案。

我在IronPython中根据http://manaspatnaik.com/blog/index.php/technology/wpf/routed-event-in-wpf-introduction/244

写了一个小小的演示

以下是代码:

import wpf

from System.Windows import Application, Window
from System.Windows.Media import Brushes
from System.Windows import EventManager
from System.Windows import RoutedEventHandler, RoutedEventArgs

class MyWindow(Window):
    def __init__(self):
        wpf.LoadComponent(self, 'WpfTestApplication1.xaml')

        #self.MyPanel.MouseMove += self.Mouse_Move_Handler

        delegate = RoutedEventHandler(self.Mouse_Move_Handler)
        self.routed_events = EventManager.GetRoutedEvents()
        mouse_move_event = [ev for ev in self.routed_events if ev.Name =='MouseMove'][0]
        self.MyPanel.AddHandler(mouse_move_event,delegate)

        self.MyPanel.MouseLeave += self.Mouse_Leave_Handler
        self.MyButton.MouseMove += self.Button_Handler
        self.MyButton.Click += self.Button_Click
        self.MyButton.Click += self.Button_Click

    def Mouse_Move_Handler(self, sender, e):
        self.MyPanel.Background = Brushes.Red
        self.MyLabel.Content = 'Inside Panel'

    def Mouse_Leave_Handler(self,sender,e):
        self.MyPanel.Background = Brushes.Cyan
        self.MyLabel.Content = 'Outside Panel'

    def Button_Handler(self, sender, e):
        self.MyPanel.Background = Brushes.DarkBlue
        e.Handled = True

    def Button_Click(self, sender, event):
        self.MyLabel.Background = Brushes.SaddleBrown

if __name__ == '__main__':
    win = MyWindow()
    Application().Run(win)

现在行为似乎完全一样。 AddHandler例程有原因吗? 也有人可能会考虑到这样做:

 AddHandler(self.MouseMove,delegate) or AddHandler(Window.MouseMove,delegate)

导致错误:

ArgumentTypeException was unhandled by user code
expected RoutedEvent, got BoundEvent

任何人都可以澄清情况吗?区别在哪里?

编辑:通过使用Control.MouseMoveEvent而不是从EventManager中提取mouse_move_event,可以通过这两行来减少代码:

    #self.routed_events = EventManager.GetRoutedEvents()
    #mouse_move_event = [ev for ev in self.routed_events if ev.Name =='MouseMove'][0]

我真的看不出任何差异。

0 个答案:

没有答案