Reputation: 3
I have a page with a Grid on it.
Based on the selection of a ComboBox I dynamically add an appropriate GridView that has a ContextMenu (so far so good).
One of the ContextMenuItem options needs user input so I dynamically build and add controls to a Grid, and add the Grid as a child of the Grid on the Page (at the same time I hide the first child of the Grid (the GridView)).
The controls don't appear in the expected positions. If I specify 0,0,0,0 they show up somewhere around the middle. If I specify -800, -400, 0,0 they show up close to where I want them to be but not where they are expected to be (the Grid itself is 800x400).
Am I missing something?
I've tried adding columns and rows and specifying position that way. I've tried setting margins of the controls directly. Nothing seems to work as expected.
Thanks
Upvotes: 0
Views: 154
Reputation: 5723
To position the controls you can do it in several ways. You should use Canvas
element instead of Grid
and set Left
and Top
properties in controls you want to position.
Sample in XAML to position button in (30, 10):
<Canvas>
<Button x:Name="sampleButton"
Width="30" Height="20"
Canvas.Left="30"
Canvas.Top="10"/>
</Canvas>
Sample in code behind:
...
Canvas.SetLeft(sampleButton, 30);
Canvas.SetTop(sampleButton, 10);
...
If you, however, need to use Grid
(for some reason), you can set HorizontalAlignment
to Left
and VerticalAlignment
to Top
, specify appropriate values for Width
and Height
and THEN set Margin to x, y, 0, 0.
A sample code:
<Grid>
<Button x:Name="sampleButton"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Width="30" Height="20"
Margin="30, 10, 0, 0"/>
</Grid>
Upvotes: 0
Reputation: 44316
You should be using a Canvas
if you are positioning controls exactly. A Grid
is designed to position controls relatively, whereas it looks like you are trying to position them absolutely (within the Grid
).
Upvotes: 1