WPF FrameworkElement鼠标点击问题

发布于 2024-10-14 13:09:54 字数 1183 浏览 5 评论 0原文

在 WPF 应用程序中,我在网格内有一堆自定义控件。为了处理鼠标单击它们,我使用网格的 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 中,然后放入网格中时,出现了问题。在这种情况下,该方法不起作用。
我通过 e.Source.GetType().ToString(); 检查了每种情况下的点击源类型,并得到以下结果:

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

MyProjectNamespace.MyCustomControl

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

MyProjectNamespace.UserControls.MyUserControlName

当我将 CustomControls 放入 UserControl,然后放入网格并通过 XamlReader.Load 从外部文件加载 UserControl

System.Windows.Controls.UserControl

那么,我的问题:
当 CustomControls 位于 UserControl 内部时,如何使它们可视为 e.Source

In a WPF app I have I bunch of CustomControls inside a Grid. For processing Mouse clicks on them I use the MouseLeftButtonDown event of the Grid and in the event handler I check which CustomControl was clicked:

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

The problem appeared when I placed all CustomControls in a UserControl and then inside the Grid. In this case approach doesn't work.
I checked the type of click source in each case by e.Source.GetType().ToString(); and get the following results:

When there are no problem (in case I put CustomControls in the Grid without UserControl)

MyProjectNamespace.MyCustomControl

When I put CustomControls in the UserControl and then in the Grid

MyProjectNamespace.UserControls.MyUserControlName

When I put CustomControls in the UserControl and then in the Grid and load the UserControl from external file by XamlReader.Load

System.Windows.Controls.UserControl

So, my question:
How to make CustomControls vizible as e.Source when they are inside of a UserControl?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里的微风 2024-10-21 13:09:54

e.OriginalSource 将告诉您点击发生在哪个特定元素上。如果这不是您的自定义控件,请沿着 OriginalSource 的父链向上查找,直到找到您的自定义控件

e.OriginalSource will tell you which specific element the click happened on. if that is not your customcontrol, walk up the Parent chain of the OriginalSource until you find your customcontrol

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文