我想知道如何在代码后面创建一个包含Stackpanel作为容器的按钮 和stackpanel里面的textblock一样,当我试图创建按钮时,它会在Stackpanel中抛出Null Exception.Kindly帮我解决这个问题。
我尝试的是:
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;
}
答案 0 :(得分:1)
在你的代码中,你实际上并没有使用st的值。我相信你最后要做的是b.Content = st;
而不是st = b.Content as Grid