Search code examples
c#windows-phone-7

Programmatically enable a disabled checkbox in a Windows Phone 7 app


I'm writing my first device-specific application which is a Windows Phone 7 panorama app. I'm currently still busy on the UI as I'm playing around with the features then I stumbled upon a problem that I couldn't fix. You see, I have two checkboxes for some sort of login form. One is a "Remember me" and the other a "Sign me in automatically" checkbox. The action I want is that when I uncheck Remember Me, I would like the Sign in Automatically checkbox to be unchecked and disabled. That I was able to do but the reverse always causes an error. I used to write simple PHP web apps and JavaScript so I have some programming knowledge but C# is fairly new to me.

private void RememberMe_Unchecked(object sender, RoutedEventArgs e)
{
    AutoSignIn.IsChecked = false;
    AutoSignIn.IsEnabled = false;
}

That one works but this one doesn't:

private void RememberMe_Checked(object sender, RoutedEventArgs e)
{
    AutoSignIn.IsEnabled = true;
}

The latter throws a "NullReferenceException was unhandled" error.

My XAML code looks like this:

<CheckBox Content="Remember me" Height="71" Name="RememberMe" Unchecked="RememberMe_Unchecked" Checked="RememberMe_Checked" IsEnabled="True" IsChecked="True" />
<CheckBox Content="Sign me in automatically" Height="71" Name="AutoSignIn" IsEnabled="True" IsChecked="True" />

I've done some research and my approach seem to be wrong but I'm not sure how to make it work.


Solution

  • Without the XAML I can't be 100% sure, but make sure you are not setting the IsChecked property programmatically. When you do so, the IsChecked method will get called once before everything is initialised properly on the page. So while the code posted by Matt works:

    <CheckBox Name="AutoSignIn" />
    <CheckBox Name="RememberMe" Checked="RememberMe_Checked" Unchecked="RememberMe_Unchecked" />
    

    The following won't (because it tries to reference the AutoSignIn box before the page has finished initializing)

    <CheckBox Name="AutoSignIn" />
    <CheckBox Name="RememberMe" IsChecked="True" Checked="RememberMe_Checked" Unchecked="RememberMe_Unchecked" />
    

    To fix this, you can set the IsChecked property programmatically instead of in XAML, or there might be some other way around this that someone else can point you to.