A Button
contains a Grid
. The structure is like the follows:
<Button>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Viewbox Grid.Column="0">
<TextBlock></TextBlock>
</Viewbox>
<Viewbox Grid.Column="1">
<TextBlock></TextBlock>
</Viewbox>
</Grid>
</Button>
The problem is that the TextBlock
s position aren't fixed, so you can see the following situation, where the gridline is moved to the right when the text on left becomes longer. How to make the TextBlock
s position fixed inside the grid cell (so the middle grid line stays regardless of the text length)?
EDIT: The above XAML will fix the positons of the TextBlocks as it is, but will not work when the Grid
is inside a button. Images below of a Grid with blue background on a silver button: we can see the grid line changes as the text changes (while the ratio stays the same?) primarily because the Grid occupies different region of the Button.
So guess my real question is: How to make the Grid
occupy the entire Button? (if the grid stays fixed, so does its grid line.)
EDIT2:
Below is the code that generates the Button, Grid, Viewbox, TextBlock structure represented by the above XAML. This code generates the Button
s as shown below, where the green Grid
does not stretch to the entire blue Button
and its occupied area differs based on its content. Setting Grid's properties as g.HorizontalAlignment = HorizontalAlignment.Stretch;
g.VerticalAlignment = VerticalAlignment.Stretch;
doesn't work.
Button b = new Button();
b.Background = Brushes.DeepSkyBlue;
Grid g = new Grid();
g.Name = "grid";
g.ShowGridLines = true;
g.Background = Brushes.LimeGreen;
g.HorizontalAlignment = HorizontalAlignment.Stretch;
g.VerticalAlignment = VerticalAlignment.Stretch;
//create columns
for (int i = 0; i < 2; i++)
{
int len = i == 0 ? 3 : 1;
ColumnDefinition cd = new ColumnDefinition();
cd.Width = new GridLength(len, GridUnitType.Star);
g.ColumnDefinitions.Add(cd);
}
//viewbox col 0
Viewbox vb = new Viewbox();
TextBlock tb1 = new TextBlock();
vb.Child = tb1;
Grid.SetRow(vb, 0);
Grid.SetColumn(vb, 0);
g.Children.Add(vb);
//viewbox col 1
Viewbox vb2 = new Viewbox();
TextBlock updown = new TextBlock();
vb2.Child = updown;
//specify the Marlett Font
updown.Style = (Style)Application.Current.FindResource("updownBlock");
Grid.SetRow(vb2, 0);
Grid.SetColumn(vb2, 1);
g.Children.Add(vb2);
//add grid to button
b.Content = g;