I want to add canvas elements by user input. Something like when a button is clicked, a new <Ellipse/> element is added to the XAML file, inside the Canvas.
<Canvas x:Name="GraphDisplayFrame" Grid.Column="1" Grid.Row="0" Grid.ColumnSpan="3" Grid.RowSpan="4">
<Ellipse
Width="50"
Height="50"
Stroke="Black"
StrokeThickness="2"
Canvas.Left="100"
Canvas.Top="100" />
</Canvas>
I'm new to WPF, i'm not sure if this is the right way to do this.
The other thing i'm trying is System.Windows.Media but manipulating the XAMl file looks easier and nicer, since then the locations of the drawings are anchored to the canvas. I'm not sure if i can achieve something similar with System.Windows.Media.
So my question is in the title, but I'm open to other suggestions.
You probably want to learn about Bindings in WPF. Let's say you want your
Ellipses be added by user's input (e.g. onButtonclick) to yourCanvas. I'm not sure about Canvas usage for that purpose (it hasn't auto-alignments for child elements), so I usedWrapPanelinstead (to allow it align items). And we need 2Buttons (to Add and RemoveEllipses). And I add aLabelto display current amount of Ellipses that we have.XAML:
Here you see that
Label.Contentproperty is binded to some EllipsesCount property (you'll see it in code-behind below). Also asWrapPanelis binded to Ellipses property.Code-behind: (for copypaste purpose)
So at result you see, actually, "content of collection of Ellipses", without adding Ellipses directly to window. Binding makes
WrapPanelto use collection of Ellipses as source of child elements, that should be in thatWrapPanel(instead of original my answer, where we add Ellipse to Canvas as Children).ORIGINAL answer.
Yes, you can. For example (based on your XAML):
XAML (empty window):
Code-behind (check comments also):
So, as you can see, XAML markuping is quite more compact, that code-behinded one.