Reputation: 5813
In WPF, to set the vertical location of an ellipse, for instance, one uses the method Canvas.SetTop(ellipseObj, y)
. That is to say, the location is stored in the class Canvas and not in the canvas object that contains the ellipse!
I like to understand why! So, why are attached properties stored as class variables?
Upvotes: 1
Views: 155
Reputation: 102793
Attached properties are implemented that way so that any framework element (say a Line, or a TextBox) can be given a relationship to another object (say a Canvas, or a Grid), that it knows nothing about. Properties like Left
and Top
correctly belong to the container control, which is responsible for arranging its child element.
You can think of it like a visitor pattern -- the Canvas container is able to effectively modify the behavior of any child elements, without actually changing the structure of those elements.
Here's how the MSDN article on attached properties explains it:
One purpose of an attached property is to allow different child elements to specify unique values for a property that is actually defined in a parent element.
Upvotes: 1
Reputation: 12849
The point of WPF is, that UI Panels
decide where their child elements are drawn. So, controls themselves have no say about where they can be positioned. In measure pass of UI layout, only control's size is considered.
In your case, you are using Canvas
as example, which is quite short-sighted. Canvas is only one of the few possible ways to layout child controls and only it was designed to allow precise positioning of it's child elements. So it makes sense to be able to set Top and Left values for each child. And just to note, Canvas is least-advised way to layout your UI.
But in Grid
, no such thing is possible. Here, you set which Row
, Column
and what RowSpan
and ColSpan
should child have. And in DockPanel
, you have different ways to dock the child elements.
And other panels like StackPanel
and WrapPanel
have no such options.
To solve this, you have 2 options:
Also, Attached Properties are useful for many other things, than panel layout.
Upvotes: 2