Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is my StackPanel not in the generated class? (NullReferenceException)
    text
    copied!<p>I'm getting a NullReferenceException in my code in the call to checkBox2_Checked. The exception indicates that stackPanelListbox is null. It's declared in the XAML, and a similarly declared stackPanel is not null. What is wrong here? </p> <p>Here's the XAML:</p> <pre><code>&lt;Window x:Class="ch0103.WPF.LayoutWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="LayoutWindow" Height="450" Width="900"&gt; &lt;StackPanel Name="stackPanelMain"&gt; &lt;WrapPanel&gt; &lt;CheckBox Name="checkBox1" VerticalAlignment="Center" IsThreeState="False" IsChecked="True" Click="checkBox_Checked" Content="Button StackPanel" Margin="0,0,11,0" /&gt; &lt;CheckBox Content="Listbox StackPanel" Height="16" Name="checkBox2" IsChecked="True" Checked="checkBox2_Checked" /&gt; &lt;/WrapPanel&gt; &lt;Grid Name="grid1" ShowGridLines="True"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="Auto" /&gt; &lt;ColumnDefinition /&gt; &lt;ColumnDefinition /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;StackPanel HorizontalAlignment="Left" Name="stackPanelButtons" VerticalAlignment="Top" Visibility="Visible"&gt; &lt;Button Content="Button" Height="23" Name="button1" /&gt; &lt;Button Content="Button" Height="23" Name="button2" /&gt; &lt;Button Content="Button" Height="23" Name="button3" /&gt; &lt;/StackPanel&gt; &lt;StackPanel Name="stackPanelListbox" Grid.Column="1"&gt; &lt;ListBox Grid.Column="2" HorizontalAlignment="Left" Name="listBox1" VerticalAlignment="Top" Width="200"&gt; &lt;ListBoxItem Content="Test" /&gt; &lt;ListBoxItem Content="Test" /&gt; &lt;ListBoxItem Content="Test" /&gt; &lt;ListBoxItem Content="Test" /&gt; &lt;ListBoxItem Content="Test" /&gt; &lt;ListBoxItem Content="Test" /&gt; &lt;ListBoxItem Content="Test" /&gt; &lt;/ListBox&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>Here's the c# code: </p> <pre><code>using System.Windows; namespace ch0103.WPF { /// &lt;summary&gt; /// Interaction logic for LayoutWindow.xaml /// &lt;/summary&gt; public partial class LayoutWindow : Window { public LayoutWindow() { InitializeComponent(); } private void checkBox_Checked(object sender, RoutedEventArgs e) { stackPanelButtons.Visibility = (bool) checkBox1.IsChecked ? Visibility.Visible : Visibility.Collapsed; } private void checkBox2_Checked(object sender, RoutedEventArgs e) { stackPanelListbox.Visibility = (bool) checkBox2.IsChecked ? // stackPanelListbox is null here? Visibility.Visible : Visibility.Collapsed; } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload