In WPF applications, you may need to dynamically add a set of rectangles according to the data. This can be implemented by model-view-view model (MVVM) mode.
Consider a view model, which contains a rectangular collection of an abstract indicated by the
object:
RectItem
<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; } }</code>
<code class="language-csharp">public class ViewModel { public ObservableCollection<RectItem> RectItems { get; set; } = new ObservableCollection<RectItem>(); }</code>
Canvas
to display this collection: ItemsPanel
ItemsControl
<code class="language-xml"><ItemsControl ItemsSource="{Binding RectItems}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas /> </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 Fill="Black" Height="{Binding Height}" Width="{Binding Width}" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl></code>
RenderTransform
<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}"> <Rectangle.RenderTransform> <TranslateTransform X="{Binding X}" Y="{Binding Y}" /> </Rectangle.RenderTransform> </Rectangle> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl></code>
The above is the detailed content of How can I dynamically display rectangles in a WPF application using the MVVM pattern?. For more information, please follow other related articles on the PHP Chinese website!