C#WPF根据界面显示的图片输入一个起始点像素坐标和终止点像素坐标,根据这两个界面在图片上绘制一个矩形框,实现模式为MVVM模式,坐标输入在ViewModel层,矩形绘制在View层
时间: 2024-12-18 13:35:09 浏览: 93
在C# WPF应用中,采用MVVM(Model-View-ViewModel)模式时,处理图片上绘制矩形的操作通常会分步骤进行:
1. **Model(模型)**: 这里需要定义一个包含起始点(StartPoint)和终止点(EndPoint)属性的`ImageRectangleViewModel`类,这些属性可以是`double`类型的坐标值。
```csharp
public class ImageRectangleViewModel
{
public double StartPointX { get; set; }
public double StartPointY { get; set; }
public double EndPointX { get; set; }
public double EndPointY { get; set; }
}
```
2. **View Model(视图模型)**: 在`ImageRectangleViewModel`中添加方法,比如`DrawRectangle`,它会接受起始点和结束点作为参数,并根据需求更新视图。
```csharp
private void DrawRectangle(double startPointX, double startPointY, double endPointX, double endPointY)
{
// 根据传入的坐标计算矩形范围,这里只是一个示例
var rect = new Rect(new Point(startPointX, startPointY), new Size(endPointX - startPointX, endPointY - startPointY));
// 更新UI绑定或通知View更新
OnPropertyChanged(nameof(RectangleGeometry));
}
// 当坐标改变时,更新矩形信息
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
```
3. **View(视图)**: 在XAML中,有一个图片控件(如`Image`或`Canvas`),需要设置数据绑定到`ImageRectangleViewModel`,并监听其`RectangleGeometry`属性的变化。例如:
```xaml
<Canvas>
<Image Name="MyImage" Stretch="Fill">
<Image.DrawingContext>
<DrawingContext>
<!-- 在此处获取ViewModel的RectangleGeometry -->
<RectangleGeometry DataTrigger Binding="{Binding RectangleGeometry}" />
</DrawingContext>
</Image.DrawingContext>
</Image>
</Canvas>
<!-- 在C# Code Behind 或依赖项注入中调用DrawRectangle方法 -->
private void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "RectangleGeometry")
{
MyImage.DrawingContext.DrawRectangle(Pen, Brush, ViewModel.RectangleGeometry);
}
}
```
**相关问题--**
1. MVVM模式下,如何在View中响应ViewModel的数据变化?
2. 如何保证起始点和终止点的有效性,防止越界?
3. 如何在ViewModel中处理用户输入的坐标转换为屏幕坐标?
阅读全文
相关推荐


















