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

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

问题描述

根据点的集合绘制一个位图图像(1024 x 1024像素)和矩形。矩形应该完全适合图像上的像素位置。

To draw one Bitmap Image (of 1024 x 1024 pixels) 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>

上面假设你的虚拟机通过 code>属性,并且每个点虚拟机具有 X Y 高度属性。

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天全站免登陆