Search code examples
xamlposition

Change position of controls when I resize a window WPF 2010


When an application is not opened in Full Screen then it works very well. However, when I open Full Screen then my buttons and “StudentsDataGrid” lose their positions and I cannot see where they are. Buttons and DataGrid alter their positions when I resize the window as well as. Here xaml is:

<Window x:Class="StudentsBoard.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        
    Title="MainWindow" Height="996" Width="1191" 
    xmlns:my="clr-namespace:Students" Loaded="Window_Loaded"        
    WindowStartupLocation="CenterScreen" WindowStyle="SingleBorderWindow"  
    ResizeMode="CanResize" SizeChanged="Window_SizeChanged" SizeToContent="Manual" 
    WindowState="Maximized">

    <Grid Name="MainGrid" DataContext="{StaticResource StudentViewSource}">

    <Button Content="..." Height="40" HorizontalAlignment="Left"      
    VerticalAlignment="Top" Margin="1079,132,0,785" Name="btnbar_edit_student" Style="{DynamicResource GlassButtonBar}" Width="40" Click="btnbar_edit_student_Click" />
    <Button Content="-" Height="40" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="1079,192,0,725" Name="btnbar_del_student" Style="{DynamicResource GlassButtonBar}" Width="40" Click="btnbar_del_student_Click" />

    <DataGrid AutoGenerateColumns="False" EnableRowVirtualization="True" Height="177"           
    HorizontalAlignment="Left" VerticalAlignment="Top" ItemsSource="{Binding Source= 
    {StaticResource StudentViewSource}}" Margin="868,60,0,0" Name="StudentsDataGrid"    
    RowDetailsVisibilityMode="VisibleWhenSelected" Width="192"   
    MouseLeftButtonUp="StudentsDataGrid_MouseLeftButtonUp">                        
          </DataGrid>
    </Grid>

I want that elements stay the exact same positions. What is the decision?


Solution

  • You can do so by using HorizontalAllignment=Stretch and VerticalAllignment = Stretch for the controls present in the grid.

    Alternative solution for this can also be defining rows and columns for your grid. e.g,`

                <ColumnDefinition Width="222*" />
                <ColumnDefinition Width="211" />
                <ColumnDefinition Width="159" />
                <ColumnDefinition Width="282*" />
            </Grid.ColumnDefinitions>
    

    `

    Best approach for such situtaion will be to use Panel layouts provided by WPF. Such as DockPanel, StackPanel.