简体   繁体   中英

Accessing CheckBox property from click event handler in Xamarin.Android

If I write the event handler like this:

CheckBox whatever = FindViewById<CheckBox> (Resource.Id.checkBox1);
whatever.Click += (s, e) =>
{
    if (!whatever.Checked)
    {
    //do stuff
    }
}

an exception is thrown when the handler is called. If I create another CheckBox object for the same view with a different name- like this:

CheckBox whatever = FindViewById<CheckBox> (Resource.Id.checkBox1);
whatever.Click += (s, e) =>
{
    CheckBox whatever2 = FindViewById<CheckBox> (Resource.Id.CheckBox1);
    if (!whatever2.Checked)
    {
    //do stuff
    }
}

there are no issues. Why is the duplicate object required?

That is a weird issue if the checkBox1 & CheckBox1 mismatch is a typo. In any case you might be better of using the CheckedChanged event. All the below scenarios run just fine so there's probably something else in the code that doesn't match. Is the Id on the layout checkBox1 or CheckBox1?

        var checkBox = FindViewById<CheckBox>(Resource.Id.CheckBox1);

        checkBox.CheckedChange += (sender, args) =>
        {
            if (!args.IsChecked)
            {

            }
        };

        checkBox.Click += (sender, args) =>
        {
            if (!checkBox.Checked)
            {

            }

            if (!((CheckBox)sender).Checked)
            {

            }
        };

In what method you assign the whatever control?

protected override void OnResume()
{
    base.OnResume();

    CheckBox whatever = FindViewById<CheckBox>(Resource.Id.checkBox1);
    if (whatever != null) //Verify the state of your whatever object to avoid exception
    {
        whatever.Click += (s, e) =>
        {
            if (!whatever.Checked)
            {
                //do stuff
            }
        };
    }
}

I always declare my controls inside OnResume event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM