WinUI3 : Absolute positionig of UIElement

Harshithraj1871 1,706 Reputation points
2022-12-12T12:37:25.443+00:00

Hi,

I was trying to achieve absolute positioning in WinUI3 and got to know that the GUI child elements are built relative to the parent element(Page, Grid and etc). So to achieve absolute positioning we have to wrap the UIElement in a canvas and set the a X and Y to the Canvas to do absolute positioning,

But in the application build of large number of UIElement, it would not be the best practice to use 2 UIElement[Canvas and UIElement] for each UIElement. Is there any way where we can achieve absolute positioning without canvas or any kind of wrapper?

Thank You

Windows development | Windows App SDK
Developer technologies | C++
{count} votes

1 answer

Sort by: Most helpful
  1. Junjie Zhu - MSFT 21,646 Reputation points
    2022-12-13T06:23:26.28+00:00

    Hello @Harshithraj1871 ,
    Welcome to Microsoft Q&A!

    Here is a workaround, using Margin and VerticalAlignment="Top", this can achieve a similar absolute positioning.

    Mainwindows.xaml

    <Window  
       ...  
        <Grid x:Name="testGrid">  
            <Button x:Name="myButton"  VerticalAlignment="Top" Height="88" Width="146" Margin="200,200,0,0">Click Me</Button>  
            <TextBox x:Name="txtBoxX" HorizontalAlignment="Left" Margin="546,36,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top"/>  
            <TextBox x:Name="txtBoxY" HorizontalAlignment="Left" Margin="652,36,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top"/>  
            <Button Content="Button" Margin="768,36,0,0" VerticalAlignment="Top" Click="Button_Click"/>  
        </Grid>  
    </Window>  
    

    Mainwindows.xaml.cs

       private void Button_Click(object sender, RoutedEventArgs e)  
        {  
            int pointX = int.Parse(txtBoxX.Text);  
            int pointY = int.Parse(txtBoxY.Text);  
            Thickness thickness = new Thickness();  
            thickness.Top = pointX;  
            thickness.Left = pointY;  
            thickness.Right = 0;  
            thickness.Bottom = 0;  
    
            myButton.Margin = thickness;  
        }  
    

    269942-gif-12-13-2022-2-21-26-pm.gif

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.