WPF Canvas, how to add children dynamically with MVVM code behind WPF Canvas, how to add children dynamically with MVVM code behind wpf wpf

WPF Canvas, how to add children dynamically with MVVM code behind


ItemsControl is your friend:

<Grid>    <Image Source="..."/>    <ItemsControl ItemsSource="{Binding Points}">        <ItemsControl.ItemsPanel>            <ItemsPanelTemplate>                <Canvas/>            </ItemsPanelTemplate>        </ItemsControl.ItemsPanel>        <ItemsControl.ItemContainerStyle>            <Style>                <Setter Property="Canvas.Left" Value="{Binding X}"/>                <Setter Property="Canvas.Top" Value="{Binding Y}"/>            </Style>        </ItemsControl.ItemContainerStyle>        <ItemsControl.ItemTemplate>            <DataTemplate>                <Border BorderBrush="Red" BorderThickness="1" Width="{Binding Width}" Height="{Binding Height}"/>            </DataTemplate>        </ItemsControl.ItemTemplate>    </ItemsControl></Grid>

The above assumes your VM exposes a collection of points via a Points property, and that each point VM has X, Y, Width, and Height properties.


Added IsItemsHost="True" to the Canvas of Kent's solution:

<Grid>    <Image Source="..."/>    <ItemsControl ItemsSource="{Binding Points}">        <ItemsControl.ItemsPanel>            <ItemsPanelTemplate>                <Canvas  IsItemsHost="True"/>            </ItemsPanelTemplate>        </ItemsControl.ItemsPanel>        <ItemsControl.ItemContainerStyle>            <Style>                <Setter Property="Canvas.Left" Value="{Binding X}"/>                <Setter Property="Canvas.Top" Value="{Binding Y}"/>            </Style>        </ItemsControl.ItemContainerStyle>        <ItemsControl.ItemTemplate>            <DataTemplate>                <Border BorderBrush="Red" BorderThickness="1" Width="{Binding Width}" Height="{Binding Height}"/>            </DataTemplate>        </ItemsControl.ItemTemplate>    </ItemsControl></Grid>