In the WPF MVVM mode, add rectangle to Canvas
Solution
<.> 1. Abstract indication:Create a ViewModel, which contains abstract representations of rectangular lists, for example:
<.> 2. XAML means:
<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>
<.> 3. Data binding:
Bind the
<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>
attribute of . This will automatically generate a rectangle to each item in the collection.
<.> 4. style binding (optional): RectItems
ItemsControl
You can choose to use style binding, set ItemsSource
and
<.> 5. Alternative scheme (no style binding):
If the style is bound to your environment (such as UWP), you can use rendering transformation in the rectangular template: Canvas.Left
Canvas.Top
The above is the detailed content of How to Dynamically Add Rectangles to a WPF Canvas Using MVVM?. For more information, please follow other related articles on the PHP Chinese website!