【问题标题】:Moveable Custom Control可移动的自定义控件
【发布时间】:2011-12-10 20:02:06
【问题描述】:

我有一个自定义控件,我希望用户能够拖动它。所以我在自定义控件中放入了如下代码:

    void MoveableStackPanel_MouseMove(object sender, MouseEventArgs e)
    {
        if (IsMoving)
        {
            Point newLoc = e.GetPosition(null);
            MainWindow.Instance.Title = newLoc.ToString(); // Debug
            Margin = new Thickness(newLoc.X - 48, newLoc.Y - 48, 0, 0);
        }
    }

注意代码中的“-48”。 当鼠标向上或向左移动时,鼠标不在控制区域中,因此不再触发 MouseMove 事件。所以我添加了两次 -48 来解决这个问题。但是当用户移动鼠标的速度快于框架的更新速度时,鼠标就会移到控件区域之外,控件也不会再移动了。

我正在考虑分配一个 IMovableInterface 并保留在主窗体中移动的控件列表等,但这太麻烦了……什么是正确的解决方案?

P.S.:控件是动态生成的,所以我需要 C# 代码而不是 XML 中的解决方案。

【问题讨论】:

    标签: c# wpf controls


    【解决方案1】:

    尝试使用CaptureMouse Method

    看看这样的东西是否适合你。:

    void moveableStackPanel1_MouseUp(object sender, MouseButtonEventArgs e)
        {
            ReleaseMouseCapture();
        }
    
        void moveableStackPanel1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (IsEnabled && IsVisible)
                CaptureMouse();
        }
    
        void moveableStackPanel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (IsMouseCaptured)
            {
                Point newLoc = e.GetPosition(null);
                Margin = new Thickness(newLoc.X, newLoc.Y, 0, 0);
            }
        } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多