Cannot Get WPF Appearance I Want

RogerSchlueter-7899 1,526 Reputation points
2021-07-06T03:56:51.613+00:00

Assume a grid in a wpf window. I want a "cell" of that grid to be a specified color and I want the controls in that cell to be centered. For example, consider the window below which contains a 2x2 grid with a StackPanel in cell (1,1) generated by the following XAML:

<StackPanel  
	Background="#64E8BE"  
	Grid.Column="1"  
	Grid.Row="1"  
	Margin="0,0,5,0"  
	HorizontalAlignment="Center"  
	Orientation="Horizontal">  
	<Label  
		Content="A Label"  
		FontSize="12"  
		FontWeight="Bold"  
		Margin="0,0,5,0">  
	</Label>  
	<Button  
		Background="Transparent"  
		BorderThickness="0"  
		Content="Button"  
		FontSize="12"  
		FontWeight="Bold">  
	</Button>  
</StackPanel>  

which yields:
112006-p2.png

If I remove the HorizontalAlignment="Center" line from the StackPanel, I get:
111946-p1.png

In summary, I can get the controls centered OR I can color the whole cell but I cannot figure out how to get both.

Developer technologies | Windows Presentation Foundation
Developer technologies | XAML
Developer technologies | XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Emon Haque 3,176 Reputation points
    2021-07-06T05:27:45.93+00:00

    Use Grid inside Grid like this:

    <Grid Margin="20">  
        <Grid.RowDefinitions>  
            <RowDefinition/>  
            <RowDefinition/>  
        </Grid.RowDefinitions>  
        <Grid.ColumnDefinitions>  
            <ColumnDefinition/>  
            <ColumnDefinition/>  
        </Grid.ColumnDefinitions>  
        <Grid Background="#64E8BE">  
            <Grid.ColumnDefinitions>  
                <ColumnDefinition/>  
                <ColumnDefinition/>  
            </Grid.ColumnDefinitions>  
            <Label Content="A Label"  
                   FontSize="12"  
                   FontWeight="Bold"  
                   HorizontalAlignment="Center"  
                   VerticalAlignment="Center"/>  
    
            <Button Grid.Column="1"  
                    Background="Transparent"  
                    HorizontalAlignment="Center"  
                    BorderThickness="0"  
                    Content="Button"  
                    FontSize="12"  
                    FontWeight="Bold"/>  
        </Grid>  
    

    to have something like this:

    111968-capture.png

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

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