对Grid绑定移动

在WPF中,一般移动在Window中写

this.DragMove();

但是这样可能会污染View的纯净性质,如果不喜欢这样的写法,可以自己扩展代码
1、使用Command在ViewModel绑定
2、使用方法在Grid中自定义完成
总体思路都是一样的
现在给出我的邪门写法
首先扩展下命令行为

public static class CommandBehavior
{
    public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(CommandBehavior), new PropertyMetadata(null, CommandPropertyChanged));

    public static readonly DependencyProperty ParameterProperty = DependencyProperty.RegisterAttached("Parameter", typeof(object), typeof(CommandBehavior), new PropertyMetadata(null));

    public static void SetParameter(UIElement element, object value)
    {
        element.SetValue(ParameterProperty, value);
    }

    public static object GetParameter(UIElement element)
    {
        return element.GetValue(ParameterProperty);
    }

    public static void SetCommand(UIElement element, ICommand value)
    {
        element.SetValue(CommandProperty, value);
    }

    public static ICommand GetCommand(UIElement element)
    {
        return (ICommand)element.GetValue(CommandProperty);
    }

    private static void CommandPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is UIElement uIElement)
        {
            if (e.NewValue is ICommand)
            {
                uIElement.MouseLeftButtonDown += Element_MouseLeftButtonDown;
            }
            else
            {
                uIElement.MouseLeftButtonDown -= Element_MouseLeftButtonDown;
            }
        }
    }

    private static void Element_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (sender is UIElement element)
        {
            ICommand command = GetCommand(element);
            if (command != null && command.CanExecute(null))
            {
                command.Execute(null);
            }
        }
    }
}

接着

 public class DragMoveHelper
 {
    
     public ICommand CreateDragMoveCommand()
     {
         return new TangdaoCommand(() =>
             Application.Current.Windows.OfType<Window>()
                        .SingleOrDefault(w => w.IsActive)?.DragMove());
     }
 }

这下我们可以使用ObjectDataProvider的MothedName

<ObjectDataProvider x:Key="drag"  MethodName="CreateDragMoveCommand" ObjectType="{x:Type local:DragMoveHelper}" />

对Grid进行静态绑定方法

<Grid Background="Transparent" behavior:CommandBehavior.Command="{Binding Source={StaticResource drag}}">

可以做到不需要污染View,不需要污染ViewModel,无伤静态写出控件移动

posted @ 2025-10-27 23:19  孤沉  阅读(4)  评论(0)    收藏  举报