编程语言
首页 > 编程语言> > c#-在画布中移动按钮

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