Reputation: 31
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?
Upvotes: 3
Views: 3708
Reputation: 5234
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)
{
}
};
Upvotes: 2
Reputation: 943
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.
Upvotes: 0