Search code examples
wpfstackpanel

WPF StackPanels have spacings between them


My stackpanels have gaps between each item (TextBlocks). You can see through to whatever is behind on the background Canvas. I don't want gaps. I tried setting the margin of both the stackpanel and textblocks to zero. Didn't fix it. Creating the same thing in Blend shows no gaps (AFAIK).

stackpanel
(source: synthedit.com)
Here you can see the object behind mouse/moose showing thru the gap.

StackPanel^ tstack = gcnew StackPanel;
canvas->Children->Add( tstack );
canvas->SetLeft( tstack, 100 );
canvas->SetTop( tstack, 100 );
canvas->SetZIndex( tstack, 3 );

TextBlock^ tBlock = gcnew TextBlock();
tBlock->FontSize = 10;
tBlock->Text = L"mouse";
tBlock->Background = Brushes::LightGray;
tstack->Children->Add( tBlock );

tBlock = gcnew TextBlock();
tBlock->FontSize = 10;
tBlock->Text = L"moose";
tBlock->Background = Brushes::LightGray;
tstack->Children->Add( tBlock );

Solution

  • There should be no need to set margins. A simple test in Kaxaml confirms that there should be no gap between elements. Two possible causes would be 1) an implicit style that is set in your application resources or somewhere in the visual tree or 2) SnapsToDevicePixels=false or UseLayoutRounding=true somewhere in the visual tree.