如何绘制动态矩形分层? (MVVM-WPF)

时间:2017-06-30 08:22:30

标签: c# wpf canvas mvvm

标题解释了我的问题。我有一个根矩形,它有子矩形,也可以有子矩形。在画布上动态绘制所有这些内容的最佳方法是什么?

My Rectangle-ViewModel:

    public class SketchRectangleViewModel:ViewModelBase
    {

        public SketchRectangleViewModel(SketchRectangle sr)
        {
            _id = sr.Id;
            _x = sr.x;
            _y = sr.y;
            _height = sr.Height;
            _width = sr.Width;
            _name = sr.Name;
            _parentId = sr.ParentId;
        }

        private Guid _id;
        private int _x;
        private int _y;
        private int _height;
        private int _width;
        private Guid _parentId;
        private string _name;
        private ObservableCollection<SketchRectangleViewModel> _children = new ObservableCollection<SketchRectangleViewModel>();
        private bool _isSelected;
    }

1 个答案:

答案 0 :(得分:1)

您可以在视图模型中制作所有SketchRectangleViewModel个对象的平面集合:

How to flatten tree via LINQ?

...并将所有SketchRectangleViewModel个对象的集合绑定到ItemsControl

<ItemsControl ItemsSource="{Binding YourCollection}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas Width="100" Height="100" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Left" Value="{Binding X}"/>
            <Setter Property="Canvas.Top" Value="{Binding Y}"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Rectangle Width="{Binding Width}" Height="{Binding Height}" Fill="Green" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

请注意,您只能绑定到SketchRectangleViewModel类的公共属性,因此您需要将字段转换为属性:

public double X { get; set; }