简体   繁体   中英

How to draw dynamic rectangles hierarchical? (MVVM-WPF)

The Title explains my question I guess. I have one root rectangle which has children rectangles which can also have children rectangles. What would be the best way to draw all of them dynamically on a canvas?

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

You could make a flat collection of all SketchRectangleViewModel objects in your view model:

How to flatten tree via LINQ?

...and bind the collection of all SketchRectangleViewModel objects to an 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>

Note that you can only bind to public properties of the SketchRectangleViewModel class, so you need to turn your fields into properties:

public double X { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM