The goal of this article is to render multiple rectangles on the canvas of Mainwindow, without having to know their accurate quantity at runtime. This requires a flexible method to use the MVVM principle.
The abstract rectangle in viewmodel indicates
Create a view model that defines the abstraction of rectangular, including its X, Y coordinates and size attributes.
Views with ItemsControl and Canvas
<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 : INotifyPropertyChanged { public ObservableCollection<RectItem> RectItems { get; set; } = new ObservableCollection<RectItem>(); // INotifyPropertyChanged implementation (required for data binding) public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }</code>
In mainwindow, create an ItemSControl, which is Itemspanel as Canvas. ItemsControl will be bound to the RECTITEMS collection in the view model.
Through this setting, the number of rectangles rendered on the canvas will be determined by the number of RECTITEMS in the view model. With the change of the collection of view models, the canvas will be automatically updated to reflect the new rectangle. Please note that in order to make the data binding normal work, ViewModel needs to implement theinterface. The implementation of the interface has been added to the code example.
<code class="language-xml"><ItemsControl ItemsSource="{Binding RectItems}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <Rectangle Fill="Black" Height="{Binding Height}" Width="{Binding Width}" /> </DataTemplate> </ItemsControl.ItemTemplate> <ItemsControl.ItemContainerStyle> <Style TargetType="FrameworkElement"> <Setter Property="Canvas.Left" Value="{Binding X}" /> <Setter Property="Canvas.Top" Value="{Binding Y}" /> </Style> </ItemsControl.ItemContainerStyle> </ItemsControl></code>
instances to INotifyPropertyChanged
collection, you can dynamically add rectangle during runtime.
The above is the detailed content of How to Dynamically Add and Position Rectangles on a WPF Canvas using MVVM?. For more information, please follow other related articles on the PHP Chinese website!