我在運行時用一個ViewBox在ViewBox內部創建一個按鈕,並添加一個TextBlock。這一切工作正常,除了我似乎無法讓文本左對齊。經過一番搗鼓之後,我意識到這是因爲TextBlock不是按鈕的全部寬度。在運行時在一個wpf按鈕中左對齊文本
var row = new RowDefinition();
OrdersGrid.RowDefinitions.Add(row);
var button = new Button();
button.HorizontalAlignment = HorizontalAlignment.Stretch;
button.VerticalAlignment = VerticalAlignment.Stretch;
button.MaxHeight = 40;
button.Background = (Brush)System.Windows.Application.Current.Resources["OrangeGradient"];
button.BorderThickness = new Thickness(.1);
button.Margin = new Thickness(.1);
OrdersGrid.Children.Add(button);
Grid.SetColumn(button, 0);
Grid.SetRow(button, rowNumber);
Viewbox vb = new Viewbox();
vb.StretchDirection = StretchDirection.Both;
vb.HorizontalAlignment = HorizontalAlignment.Stretch;
TextBlock tb = new TextBlock();
tb.HorizontalAlignment = HorizontalAlignment.Stretch;
tb.Text = rowNumber + " - " + CustomerName;
tb.Padding = new Thickness(0);
tb.TextAlignment = TextAlignment.Left;
vb.Child = tb;
button.Content = vb;
如果我改變tb.HorizontalAlignment = HorizontalAlignment.Stretch;
到tb.Width = 400;
它左對齊。但是,我不能保證這是正確的大小,但它將問題縮小到TextBlock的寬度。我怎樣才能讓TextBlock(和ViewBox)成爲Button的全部寬度?