2016-07-27 90 views
0

我必须使用触摸显示器,有时使用鼠标和普通显示器。如何为不同的事件执行相同的代码

所以对于拖放用于第一是

私人无效lvAllowedPPtab2_StylusButtonDown(对象发件人,StylusButtonEventArgs E)

和用于第二

私人无效ListBox_PreviewMouseLeftButtonDown (object sender,MouseButtonEventArgs e)

之后,我必须使用发件人和e执行相同的代码。

我没有做出一个通用的代码例程。 这两个事件是相似的,都有GetPosition事件。

我可能会走错路,但我因子评分喜欢的东西:

Type eventType; 
if (_e is StylusButtonEventArgs) 
    eventType = typeof (StylusButtonEventArgs); 
else 
    eventType = typeof(MouseEventArgs); 

但我不知道怎么投E要事件类型。

谢谢

+1

你必须这样做:''if(_e is StylusButtonEventArgs) var eventargs = _e as StylusButtonEventArgs;'' –

+0

您不需要该类型。只需投它并获得你的位置。 – juharr

+0

变量不能嵌入if语句 – Luca

回答

1

您可以用

private void listView_StylusButtonDown(object sender, StylusButtonEventArgs e) { CommonCode(sender, e); } 

    private void listView_PreviewMouseLeftButtonDown(object sender, MouseEventArgs e) { CommonCode(sender, e); } 

叫他们两个,然后告诉里面的通用代码

private void CommonCode(object sender, object _e) 
    { 

     //Sender is common 
     ListView parent = (ListView)sender; 
     string strListViewButtonName = (sender as ListView).Name; 

     if (_e is StylusButtonEventArgs) 
      ... (_e as StylusButtonEventArgs).GetPosition(parent)); 
     else 
      ... (_e as MouseEventArgs).GetPosition(parent)); 

    } 

更好地执行(感谢礼阿贝尔):

private void listView_StylusButtonDown(object sender, StylusButtonEventArgs e) { CommonCode(sender, e.GetPosition((ListView)sender)); } 

    private void listView_PreviewMouseLeftButtonDown(object sender, MouseEventArgs e) { CommonCode(sender, e.GetPosition((ListView)sender)); } 


    private void CommonCode(object sender, Point p) 
    { 
     //Sender is common 
     ListView parent = (ListView)sender; 
     string strListViewButtonName = (sender as ListView).Name; 

     //you don't need getPosition since P is known 

    } 
+2

真的没有理由下来这样的事件参数。只需将处理程序的位置传递给常用方法即可。 –

+0

你说得对。这可能会更好 – Patrick

相关问题