wpf mvvmlight 实现鼠标拖拽改变rectangle大小以及旋转
时间: 2024-03-08 21:51:01 浏览: 169
要实现鼠标拖拽改变Rectangle大小以及旋转,可以使用WPF的MVVMLight框架来实现。
首先,在ViewModel中定义Rectangle的位置、大小和角度等属性,以及鼠标拖拽的事件处理函数。
```
public class MainViewModel : ViewModelBase
{
private double _left;
private double _top;
private double _width;
private double _height;
private double _angle;
public double Left
{
get { return _left; }
set { Set(ref _left, value); }
}
public double Top
{
get { return _top; }
set { Set(ref _top, value); }
}
public double Width
{
get { return _width; }
set { Set(ref _width, value); }
}
public double Height
{
get { return _height; }
set { Set(ref _height, value); }
}
public double Angle
{
get { return _angle; }
set { Set(ref _angle, value); }
}
public void OnMouseDown(object sender, MouseButtonEventArgs e)
{
// 鼠标按下时记录鼠标位置
}
public void OnMouseMove(object sender, MouseEventArgs e)
{
// 鼠标移动时根据鼠标位置计算Rectangle的位置、大小和角度
}
public void OnMouseUp(object sender, MouseButtonEventArgs e)
{
// 鼠标抬起时清空鼠标位置记录
}
}
```
接着,在View中使用MVVMLight框架提供的Binding绑定属性和事件处理函数。
```
<Window.DataContext>
<vm:MainViewModel />
</Window.DataContext>
<Grid>
<Rectangle Fill="Blue" Width="{Binding Width}" Height="{Binding Height}"
Canvas.Left="{Binding Left}" Canvas.Top="{Binding Top}"
RenderTransformOrigin="0.5,0.5">
<Rectangle.RenderTransform>
<RotateTransform Angle="{Binding Angle}" />
</Rectangle.RenderTransform>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDown">
<i:InvokeCommandAction Command="{Binding MouseDownCommand}" />
</i:EventTrigger>
<i:EventTrigger EventName="MouseMove">
<i:InvokeCommandAction Command="{Binding MouseMoveCommand}" />
</i:EventTrigger>
<i:EventTrigger EventName="MouseUp">
<i:InvokeCommandAction Command="{Binding MouseUpCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Rectangle>
</Grid>
```
最后,在ViewModel中实现鼠标拖拽事件处理函数,计算Rectangle的位置、大小和角度。
```
public RelayCommand MouseDownCommand { get; private set; }
public RelayCommand MouseMoveCommand { get; private set; }
public RelayCommand MouseUpCommand { get; private set; }
public MainViewModel()
{
MouseDownCommand = new RelayCommand(OnMouseDown);
MouseMoveCommand = new RelayCommand(OnMouseMove);
MouseUpCommand = new RelayCommand(OnMouseUp);
}
private Point _lastMousePosition;
public void OnMouseDown()
{
_lastMousePosition = Mouse.GetPosition(Application.Current.MainWindow);
}
public void OnMouseMove()
{
if (Mouse.LeftButton == MouseButtonState.Pressed)
{
var currentMousePosition = Mouse.GetPosition(Application.Current.MainWindow);
var delta = currentMousePosition - _lastMousePosition;
_lastMousePosition = currentMousePosition;
// 计算Rectangle的位置、大小和角度
}
}
public void OnMouseUp()
{
_lastMousePosition = new Point();
}
```
这样就可以通过MVVMLight框架实现鼠标拖拽改变Rectangle大小以及旋转了。
阅读全文