WPF Canvas,如何使用后面的MVVM代码动态添加子项 [英] WPF Canvas, how to add children dynamically with MVVM code behind

查看:38
本文介绍了WPF Canvas,如何使用后面的MVVM代码动态添加子项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据点的集合绘制一个位图图像和矩形.矩形应该完全适合图像上的像素位置.矩形内还有一些文字需要添加.

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.

有一个带有图像控制的画布.将动态代码添加到文件ViewImageResult.xaml.cs 后面的代码下.

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);
    }

问题:

由于我遵循 MVVM 模式,矩形的点集合在我的 ViewModel 文件 ViewImageResultModel.cs 中.我无法从 ViewModel 文件中动态添加子矩形.

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.

推荐答案

ItemsControl 是你的朋友:

<Grid>
    <Image Source="..."/>
    <ItemsControl ItemsSource="{Binding Points}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
            <Style>
                <Setter Property="Canvas.Left" Value="{Binding X}"/>
                <Setter Property="Canvas.Top" Value="{Binding Y}"/>
            </Style>
        </ItemsControl.ItemContainerStyle>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Border BorderBrush="Red" BorderThickness="1" Width="{Binding Width}" Height="{Binding Height}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

以上假设您的 VM 通过 Points 属性公开一组点,并且每个点 VM 都有 XYWidthHeight 属性.

The above assumes your VM exposes a collection of points via a Points property, and that each point VM has X, Y, Width, and Height properties.

这篇关于WPF Canvas,如何使用后面的MVVM代码动态添加子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆