WPF Canvas,如何使用MVVM代码动态添加子项
要求:
根据点的集合绘制一个位图图像和矩形。矩形应完全适合图像上的像素位置。还需要在矩形内添加一些文本。
图像始终只有一张,并且矩形将动态添加。
当前的解决方案:
使用带有图像控制的画布。在代码隐藏文件ViewImageResult.xaml.cs下添加动态代码。
private void DrawResult(int left, int right, int width, int height)
{
Border bord = new Border();
bord.BorderThickness = new Thickness(1);
bord.BorderBrush = Brushes.Red;
bord.Width = width;
bord.Height = height;
_mainCanvas.Children.Add(bord);
Canvas.SetLeft(bord, left);
Canvas.SetTop(bord, right);
}
问题:
由于我遵循 MVVM 模式,因此矩形的点集合位于我的 ViewModel 文件 ViewImageResultModel.cs 中。我无法从 ViewModel 文件动态添加子矩形。
Requirement:
To draw one Bitmap Image and rectangle(s) based on the collection of points. The rectangle should exactly fit on the pixels location over the image. There is also some text need to be added inside the rectangle.
The Image will be always only one and the rectangles will be dynamically added.
Current Solution:
Have a canvas with Image Control. Add the the dynamic code under the code behind file ViewImageResult.xaml.cs.
private void DrawResult(int left, int right, int width, int height)
{
Border bord = new Border();
bord.BorderThickness = new Thickness(1);
bord.BorderBrush = Brushes.Red;
bord.Width = width;
bord.Height = height;
_mainCanvas.Children.Add(bord);
Canvas.SetLeft(bord, left);
Canvas.SetTop(bord, right);
}
Issue:
Since i follow MVVM pattern, the collection of points for rectangle is in my ViewModel file ViewImageResultModel.cs. I am not able to add the child rectangle dynamically from the ViewModel file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ItemsControl
是您的朋友:上面假设您的 VM 通过
Points
属性公开点的集合,并且每个点 VM 都有X
、< code>Y、Width
和Height
属性。ItemsControl
is your friend:The above assumes your VM exposes a collection of points via a
Points
property, and that each point VM hasX
,Y
,Width
, andHeight
properties.将
IsItemsHost="True"
添加到 Kent 解决方案的Canvas
中:Added
IsItemsHost="True"
to theCanvas
of Kent's solution: