我该如何移动粘贴/捕捉wpf窗口

时间:2011-11-17 21:36:29

标签: c# .net wpf windows sticky

我想在移动“主”窗口时移动两个或更多粘性窗口

我想做这样的事情

private void MainWindow_PreviewMouseMove(object sender, MouseEventArgs e) {
  if (e.LeftButton == MouseButtonState.Pressed) {
    this.DragMove();
    foreach (var window in App.Current.Windows.OfType<Window>()) {
      window.Move(); // move it
    }
  }
}

我想使用此解决方案来捕捉窗口

用于WPF的捕捉/粘性/磁性Windows http://programminghacks.net/2009/10/19/download-snapping-sticky-magnetic-windows-for-wpf/

但是我该如何移动呢?

修改

在Gustavo Cavalcanti的回复之后,我做了一些想法。这是我的问题的粗略解决方案。

using System.Windows;
using System.Windows.Data;

namespace DragMoveForms
{
  /// <summary>
  /// Interaction logic for Window1.xaml
  /// </summary>
  public partial class Window1 : Window
  {
    public Window1() {
      this.InitializeComponent();
    }

    public Window1(Window mainWindow)
      : this() {

      var b = new Binding("Left");
      b.Converter = new MoveLeftValueConverter();
      b.ConverterParameter = mainWindow;
      b.Mode = BindingMode.TwoWay;
      b.Source = mainWindow;

      BindingOperations.SetBinding(this, LeftProperty, b);

      b = new Binding("Top");
      b.Converter = new MoveTopValueConverter();
      b.ConverterParameter = mainWindow;
      b.Mode = BindingMode.TwoWay;
      b.Source = mainWindow;

      BindingOperations.SetBinding(this, TopProperty, b);
    }
  }
}

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace DragMoveForms
{
  public class MoveLeftValueConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
      // ok, this is simple, it only demonstrates what happens
      if (value is double && parameter is Window) {
        var left = (double)value;
        var window = (Window)parameter;
        // here i must check on which side the window sticks on
        return left + window.ActualWidth;
      }
      return 0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
      return DependencyProperty.UnsetValue;
    }
  }
}

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace DragMoveForms
{
  public class MoveTopValueConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
      // ok, this is simple, it only demonstrates what happens
      if (value is double && parameter is Window) {
        var top = (double)value;
        var window = (Window)parameter;
        // here i must check on which side the window sticks on
        return top;
      }
      return 0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
      return DependencyProperty.UnsetValue;
    }
  }
}

1 个答案:

答案 0 :(得分:5)

在窗口的左侧和顶部使用数据绑定。使用转换器根据主窗口确定右侧/顶部。然后只是担心移动主窗口,其他人将相应地移动。