Search code examples
c#wpfstackpanel

StackPanel Won't Left Align


Ok, so new to WPF and have started to make a little UI for a project. I was wondering...

Why won't the button contents left align?

        <ToggleButton Name="toggleButtonRobotConnect" Width="93.6" Margin="20,5,5,5" Click="toggleButtonRobotConnect_Click">
            <ToggleButton.Content>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center">
                    <StackPanel Orientation="Horizontal">
                        <Ellipse Name="ellipseConnected" Height="10" Width="10" Stroke="Black" Fill="DarkGreen" Margin="1"></Ellipse>
                        <Ellipse Name="ellipseNotConnected" Height="10" Width="10" Stroke="Black" Fill="Red" Margin="1"></Ellipse>
                    </StackPanel>                        
                    <TextBlock Name="textBlockRobotConnect" Text="Connect" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="5,0,0,0"/>
                </StackPanel>
            </ToggleButton.Content>
        </ToggleButton>

Shown as below. Notice the room on the left, I want to get rid of this if possible? I thought I could by left-aligning?

enter image description here

Once I "connect" I update the text so it looks like below (notice there isn't any extra room).

enter image description here

How can I modify my XAML code so the colored "lights" are always aligned and any extra room is at the end of the TextBlock side?

Thanks!


Solution

  • Upgrade your XAML as below:

         <ToggleButton Name="toggleButtonRobotConnect" Width="93.6" Margin="20,5,5,5" HorizontalContentAlignment="Left" Click="toggleButtonRobotConnect_Click" Height="50">
            <ToggleButton.Content>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center">
                    <StackPanel Orientation="Horizontal">
                        <Ellipse Name="ellipseConnected" Height="10" Width="10" Stroke="Black" Fill="DarkGreen" Margin="1"></Ellipse>
                        <Ellipse Name="ellipseNotConnected" Height="10" Width="10" Stroke="Black" Fill="Red" Margin="1"></Ellipse>
                    </StackPanel>
                    <TextBlock Name="textBlockRobotConnect" Text="Connect" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="5,0,0,0"/>
                </StackPanel>
            </ToggleButton.Content>
        </ToggleButton>
    

    You need to add only

     HorizontalContentAlignment="Left"