ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c#-在画布中移动按钮

2019-12-02 07:06:18  阅读:305  来源: 互联网

标签:c-4-0 wpf-controls wpf c


当鼠标悬停在UIElement上并且用户按下Ctrl时,以下代码应该在画布中移动UIElement.

void keydown(Object sender, KeyEventArgs e)
        {
            if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
            {
                control++;
                if (control == 1)
                {
                    drag = true;
                    elem = (UIElement)Mouse.DirectlyOver;
                }
                else
                    drag = false;
                control %= 2;
            }
        }

        void mousemove(object sender, MouseEventArgs e)
        {
            Point p = e.GetPosition(canvas);
            if (drag)
            {
                if (elem == null) return;
                //Canvas.SetLeft(myButton, p.X);  <-- this works, but then why doesn't it work when I generalize it?
                Canvas.SetLeft(elem, p.X);
                Canvas.SetTop(elem, p.Y);
            }
        }

任何Shapes组件,例如当我将鼠标悬停在矩形上并单击控件时,矩形将移动.但是它不适用于Buttons,TextBoxes,TextViews等.有人可以解释吗?

解决方法:

Mouse.DirectlyOver的文档说:

Controls can be composed of multiple elements. DirectlyOver reports the specific element in the composite control the mouse pointer is over and not the control itself. For example, depending on which part of a Button the pointer is over, the DirectlyOver property could report the TextBox of the Content property or the ButtonChrome.

换句话说:Button由几个子元素组成,例如ButtonChrome和TextBlock(通常不是TextBox,我认为这是MSDN页面上的错字).当您调用Mouse.DirectlyOver时,您可能会得到这些元素之一,而不是Button.

由于这些元素不是Canvas的父级(它们是Button控件模板中某些东西的父级,很可能是Grid),因此设置Canvas.Left和Canvas.Top附加属性将无效.

您可能想沿着可视化树(使用VisualTreeHelper.GetParent)走,直到找到您感兴趣的拖动对象.如何确定对任何给定元素是否感兴趣取决于您自己.您可以一直进行下去,直到找到Canvas的父项,或者直到找到某种给定类型的事物为止(当找到从Control派生的事物时停下来可能是一个不错的起点).

标签:c-4-0,wpf-controls,wpf,c
来源: https://codeday.me/bug/20191202/2086689.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有