Aligning controls on both left and right side in a stack panel in WPF

后端 未结 4 1554
梦谈多话
梦谈多话 2020-12-29 19:24

I have the following code:


    
        

        
相关标签:
4条回答
  • 2020-12-29 19:41

    Just do not use a StackPanel, StackPanels stack. They do, for obvious reasons, not allow alignment in the direction in which they stack. Use a Grid, with column definitions like so:

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    
    0 讨论(0)
  • 2020-12-29 19:47

    Even though this is old, should someone come across this like I did, here's a simple solution.

    Make a new grid and inside that grid put two stack panels with different Horizontal Alignment.

    <Grid>
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
            <!--Code here-->
        </StackPanel>
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
            <!--Code here-->
        </StackPanel>
    </Grid>
    

    The possible issue is that now without extra handling the two could overlap with each other.

    0 讨论(0)
  • 2020-12-29 19:56

    User @pasx is right. You should use DockPanel and dock the RadioButton to the left side, and your StackPanel with the label to the right side.

    <DockPanel>
    
        <DockPanel 
            DockPanel.Dock="Top" 
            LastChildFill="False" >
    
            <RadioButton 
                DockPanel.Dock="Left" 
                Content="_Programs" 
                IsChecked="{Binding Path=ProgramBanksSelected}"
                IsEnabled="{Binding Path=ProgramsEnabled}" 
                Margin="8" />
    
            <StackPanel
                DockPanel.Dock="Right">
    
                <Label 
                    Content="Master" 
                    Height="28" 
                    Name="MasterFileStatus" 
                    VerticalContentAlignment="Center"/>
    
            </StackPanel>
    
        </DockPanel>
        ...
    
    0 讨论(0)
  • 2020-12-29 20:00

    As you have set the StackPanel's orientation to Horizontal, the HorizontalAlignment property won't work on child-elements. You can keep the StackPanel if you need additional controls, though I would recommend switching to a Grid (among other things) to build the layout you want.

    Also, the Grid will allow you to control the actual width of each column:

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50" />
            <ColumnDefinition Width="150" />
        </Grid.ColumnDefinitions>
    
        <RadioButton
            Grid.Column="0"
            ...
        />
    
        <Label
            Grid.Column="1"
            ...
        />
    </Grid>
    

    0 讨论(0)
提交回复
热议问题