日期:2014-05-17  浏览次数:21146 次

WPF,这种点击事件如何获取事件源
一个自定义的控件CustomControl1,样式如下:

<Grid>
   <元素1>
     <元素1.Template>
       .....
     </元素1.Template>
   </元素1>
   <元素2>
     <元素2.Template>
       .....
     </元素2.Template>
   </元素2>
   <元素3>
     <元素3.Template>
       .....
     </元素3.Template>
   </元素3>
   .....
   .....
</Grid>


CustomControl1模板内部的元素1、元素2、元素3.....都要定义MouseDown事件,由于元素太多,我想在CustomControl1定义一个总的MouseDown事件,可是MouseDown事件的Sender是CustomControl1自身,Source也是CustomControl1自身,OriginalSource则是那些元素控件模板里面的更细的元素。
怎么样才能获取到元素1、元素2、元素3......呢?

------解决方案--------------------

//自定义一个事件
public partial class UserControl1 : UserControl
{
    public event EventHandler ctrlMouseDown;

    public UserControl1()
    {
        InitializeComponent();

        foreach (UIElement item in grd.Children)
        {
            item.MouseDown += item_MouseDown;
        }
    }

    void item_MouseDown(object sender, MouseButtonEventArgs e)
    {
        ctrlMouseDown(sender, e);
    }
}

------解决方案--------------------
使用HitTest试试吧,通过总控件的鼠标事件,看看命中了那些控件
http://msdn.microsoft.com/en-us/library/ms608753(v=vs.110).aspx
------解决方案--------------------
得到的sender对应的控件是对的;
5楼提供的连接我看了,很牛,已测
List<DependencyObject> hitResultsList