wpf 用鼠标调整矩形长宽 采用mvvm架构编程实现
时间: 2023-08-10 09:25:42 浏览: 50
实现这个功能,可以参考以下步骤:
1. 在 View 中,定义一个矩形和一个鼠标事件处理函数,用于处理鼠标移动事件。
```xml
<Canvas>
<Rectangle Width="{Binding Width}" Height="{Binding Height}" Stroke="Black" StrokeThickness="1" />
<Canvas Background="Transparent" MouseMove="Canvas_MouseMove" MouseUp="Canvas_MouseUp" />
</Canvas>
```
2. 在 ViewModel 中,定义 Width 和 Height 属性,以及鼠标事件处理函数。
```csharp
public class RectangleViewModel : INotifyPropertyChanged
{
private double _width;
private double _height;
private Point _startPoint;
public double Width
{
get { return _width; }
set { _width = value; OnPropertyChanged(); }
}
public double Height
{
get { return _height; }
set { _height = value; OnPropertyChanged(); }
}
public void Canvas_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
var endPoint = e.GetPosition(sender as IInputElement);
Width = Math.Abs(endPoint.X - _startPoint.X);
Height = Math.Abs(endPoint.Y - _startPoint.Y);
}
}
public void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
_startPoint = new Point(0, 0);
}
// INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
```
3. 在 View 中,将 DataContext 绑定到 ViewModel,并且在构造函数中初始化 DataContext。
```csharp
public MainWindow()
{
InitializeComponent();
DataContext = new RectangleViewModel();
}
```
这样就完成了用鼠标调整矩形大小的功能。在鼠标移动时,ViewModel 中的 Width 和 Height 属性会被更新,并通过数据绑定更新 View 中的矩形大小。这个实现采用了 MVVM 架构,将 View 和 ViewModel 分离开来,从而实现了更好的代码组织和可测试性。