asp.net中Wpf拖拽滑动效果示例

作者:袖梨 2022-06-25

wpf其实支持拖拽是很简单的。使用drag事件或者自定义鼠标事件都是可以实现的。

今天分享一个用鼠标的点击和up事件实现的拖拽滑动效果。

IT分享wpf教程-Wpf拖拽滑动效果

首先在xaml中定义一个ScrollViewer。

 代码如下 复制代码
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 Title="MainWindow" Height="400" Width="680">
   
 
    
 
 
 

    

 
   


后台模拟一下按钮数据:

 代码如下 复制代码
///
 /// 创建按钮集合
 ///

 ///
 public void CreateNgEtry(ref Grid grid)
 {
     grid.Children.Clear();
     grid.RowDefinitions.Clear();
     grid.ColumnDefinitions.Clear();
     for (int i = 0; i < 6; i++)
     {
     }
     for (int i = 0; i < 18 + 1; i++)
     {
  grid.RowDefinitions.Add(new RowDefinition());
     }
     for (int i = 0; i < 18; i++)
     {
  grid.ColumnDefinitions.Add(new ColumnDefinition());
  for (int j = 0; j < 6; j++)
  {
      Button but = new Button();
      but.Height = 80;
      but.Width = 110;
      but.FontSize = 16;
      grid.Children.Add(but);
      System.Windows.Controls.Grid.SetColumn(but, j);
      System.Windows.Controls.Grid.SetRow(but, i);
      but.Content = "Test" + i.ToString();
  }
     }
 }

鼠标按下时的事件处理,记住当前的位置:

 代码如下 复制代码
 private void canvas_PreviewMouseDown(object sender, MouseButtonEventArgs e)
 {
     targetElement = Mouse.DirectlyOver as UIElement;
     if (targetElement != null)
     {
  targetPoint = e.GetPosition(NGEntry);
     }
 }

当鼠标拖动时:

 代码如下 复制代码

 private void canvas_PreviewMouseMove(object sender, MouseEventArgs e)
 {
     if (e.LeftButton == MouseButtonState.Pressed && targetElement != null)
     {
  var pCanvas = e.GetPosition(canvas);
  double gridtop = Convert.ToDouble(NGEntry.GetValue(Canvas.TopProperty));
  NGEntry.SetValue(Canvas.TopProperty, pCanvas.Y - targetPoint.Y);
   
     }
 }

当鼠标放下事件:

 代码如下 复制代码

 private void canvas_PreviewMouseUp(object sender, MouseButtonEventArgs e)
 {
     double gridtop = Convert.ToDouble(NGEntry.GetValue(Canvas.TopProperty));
     double gridh = NGEntry.ActualHeight;
     double viewh = canvas.ActualHeight;
     if (gridtop > 0)
     {
  NGEntry.SetValue(Canvas.TopProperty, 0d);
     }
     if (viewh + (Math.Abs(gridtop)) > gridh)
     {
  NGEntry.SetValue(Canvas.TopProperty, viewh - gridh);
     }
 }

相关文章

精彩推荐