Home >Backend Development >C++ >How to Dynamically Add Multiple Rectangles to a WPF Canvas using MVVM?
Use the MVVM mode to dynamically add any number of rectangles in WPF Canvas
View model design
View Implementation
<code class="language-csharp">public class RectItem { public double X { get; set; } public double Y { get; set; } public double Width { get; set; } public double Height { get; set; } } public class ViewModel { public ObservableCollection<RectItem> RectItems { get; set; } }</code>In the view, use itemSControl to visualize the rectangular collection:
Binded with the view model
<code class="language-xml"><ItemsControl ItemsSource="{Binding RectItems}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemContainerStyle> <Style TargetType="FrameworkElement"> <Setter Property="Canvas.Left" Value="{Binding X}" /> <Setter Property="Canvas.Top" Value="{Binding Y}" /> </Style> </ItemsControl.ItemContainerStyle> <ItemsControl.ItemTemplate> <DataTemplate> <Rectangle Fill="Black" Height="{Binding Height}" Width="{Binding Width}" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl></code>ItemsControl's itemssource property is bound to the RECTITEMS property in the view model. The rectangular Canvas.Left and Canvas.top properties are set to the X and Y attributes of their respective RECTITEM objects through data binding.
As a variant, you can use rendertransform in the rectangular template to dynamically locate the rectangle:
This method allows you to dynamically add a rectangle of any number to WPF canvas and manage them through data -bound view models, thereby improving the flexibility and maintenance of the MVVM application.
The above is the detailed content of How to Dynamically Add Multiple Rectangles to a WPF Canvas using MVVM?. For more information, please follow other related articles on the PHP Chinese website!