I'm currently working on dynamically inserting Textblocks into Stackpanels. This has to be done numerous times, and there is no way to know what the size of the Stackpanel will be beforehand.
Currently, I have something like this:
TextBlock tmp = new TextBlock {
Text = curField.FieldName,
Foreground = new SolidColorBrush(Colors.Red),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
tmp.MouseLeftButtonUp += imgFormImage_MouseLeftButtonUp;
curField.assocStackpanel.Children.Add(tmp);
curField.assocStackpanel = curField.assocStackpanel;
SelectedFields.Add(curField);
Right now, the textblock just shows up centered horizontally in the Stackpanel, but not vertically. So I need to fix that. Also, ideally I would like to be able to dynamically determine the Textblock's font size so that it will fill the available space. Right now I think it's just taking the default of (I believe) 10.
I've decided to go with the following:
double xpos = Canvas.GetLeft(curField.assocGrid);
double ypos = Canvas.GetTop(curField.assocGrid);
double width = curField.assocGrid.Width;
double height = curField.assocGrid.Height;
TextBlock tmp = new TextBlock {
Text = curField.FieldName,
Foreground = new SolidColorBrush(Colors.Red),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
FontSize = 30
};
Grid grd = new Grid();
grd.Children.Add(tmp);
Viewbox vb = new Viewbox();
vb.Child = grd;
vb.Width = width;
vb.Height = height;
cvsCenterPane.Children.Add(vb);
Canvas.SetLeft(vb, xpos);
Canvas.SetTop(vb, ypos);
curField.scaleViewbox = vb;
SelectedFields.Add(curField);
By first wrapping the textblock in a grid, and then wrapping the resulting grid in a viewbox. We get an initial 1:1 scale. Then by changing the dimensions of the viewbox, we can get the resulting fill that is desired. The one thing that I wish I could do though, but cannot find a way, is to center the resulting text inside of the scaled viewbox. Right now, it comes out left aligned even if the viewbox has space to the left. I'm not sure what the cause of this is.