WPF FrameworkElement鼠标单击问题

时间:2011-01-25 18:20:03

标签: c# wpf user-controls custom-controls frameworkelement

在WPF应用程序中,我在Grid中有一堆CustomControls。为了处理鼠标点击它们我使用Grid的MouseLeftButtonDown事件,并在事件处理程序中检查单击了哪个CustomControl:

private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        FrameworkElement feSourceComm = e.Source as FrameworkElement;
        MyCustomControl SCurrentComm = new MyCustomControl();            
        try
        {
            SCurrentComm = (MyCustomControl)feSourceComm;
        }
        catch (Exception)
        {
...

当我将所有CustomControl放置在UserControl中然后放入Grid中时出现问题。在这种情况下,方法不起作用。
我通过e.Source.GetType().ToString();检查了每种情况下的点击来源类型,并得到以下结果:

当没有问题时(如果我将CustomControls放在没有UserControl的网格中)

MyProjectNamespace.MyCustomControl

当我将CustomControls放入UserControl然后放入网格

MyProjectNamespace.UserControls.MyUserControlName

当我将CustomControls放入UserControl然后放入网格并通过XamlReader.Load

从外部文件加载UserControl时
System.Windows.Controls.UserControl

所以,我的问题:
如何将CustomControls作为e.Source在UserControl内部时显示?

1 个答案:

答案 0 :(得分:2)

e.OriginalSource会告诉您点击发生的具体元素。如果那不是您的自定义控件,请向上走OriginalSource的父链,直到找到您的自定义控件

相关问题