Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

WPF CheckBox with Default True IsChecked Value Cause NullReferenceException

$
0
0

I faced with the same error on my application and a newly start testing application.

The test is simple, two checkbox on WPF. When CheckBox1 is checked, IsChecked of CheckBox2 will be set to True too.

The problem is, when IsChecked of CheckBox1 is set to False by default, there will be no problem.

But, when the IsChecked of CheckBox1 is set to True by default, there will be NullReferenceException on CheckBox1_Checked event on application startup.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <CheckBox Name="CheckBox1" Content="This is CheckBox1" HorizontalAlignment="Left" Margin="233,76,0,0" VerticalAlignment="Top" Checked="CheckBox1_Checked" IsChecked="True"/>
        <CheckBox Name="CheckBox2" Content="This is CheckBox2" HorizontalAlignment="Left" Margin="233,128,0,0" VerticalAlignment="Top"/>
    </Grid>
</Window>

        private void CheckBox1_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox2.IsChecked = true; // This cause NullReferenceException at startup if CheckBox1.IsChecked is default true
        }


I use Visual Studio 2013 and the default C# WPF template with .Net 4.5 to test.

Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>