I want to Know How to create a button in code behind which contains Stackpanel as container and textblock inside stackpanel as child,when i was tried to create the button it throws Null Exception in Stackpanel.Kindly help me to solve this problem.
What I've tried is:
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;
}
st. I believe what you wanted to do at the end isb.Content = st;rather thanst = b.Content as Grid;