我想知道如何在代码中创建一个按钮,其中包含作为容器的堆栈面板和作为子级的堆栈面板内的文本块,当我试图创建按钮时,它会在堆栈面板中抛出空异常。请帮助我解决这个问题。
我试过的是:
foreach (var pd in Query)
{
Button b = new Button();
b.HorizontalContentAlignment = HorizontalAlignment.Stretch;
b.HorizontalAlignment = HorizontalAlignment.Left;
b.VerticalAlignment = VerticalAlignment.Top;
b.Height = 196;
b.Width = 172;
b.Margin = new Thickness(d, 0, 0, 0);
b.Style = this.Resources["ButtonStyle1"] as Style;
Grid st = new Grid();
st.HorizontalAlignment = HorizontalAlignment.Stretch;
st.Width = 160;
st.Height = 188;
TextBlock tb = new TextBlock();
tb.TextWrapping = TextWrapping.Wrap;
tb.VerticalAlignment = VerticalAlignment.Top;
tb.HorizontalAlignment = HorizontalAlignment.Stretch;
tb.FontSize = 14;
tb.Margin = new Thickness(10, 0, 0, 0);
tb.RenderTransformOrigin = new Point(0.5, 0.5);
tb.FontSize = 14;
tb.FontWeight = FontWeights.Bold;
tb.Height = 35;
TextBlock tb1 = new TextBlock();
tb1.Height = 109;
tb1.VerticalAlignment = VerticalAlignment.Bottom;
tb1.HorizontalAlignment = HorizontalAlignment.Stretch;
tb1.FontSize = 12;
tb1.TextWrapping = TextWrapping.Wrap;
b.Content = pd.ProductName;
b.FontSize = 14;
b.Background = new SolidColorBrush(Colors.Red);
ContentPanel.Children.Add(b);
b.Click += new RoutedEventHandler(b_Click);
st.Children.Add(tb);
st.Children.Add(tb1);
st = b.Content as Grid;
d += 140;
}